2 questions regarding Javascript & Jquery -
please take @ code below. function used add more text input when user click con button. don't understand 2 things.
why need this?
var = $('#p_scents p').size() + 1;
don't understand used for. tested , see function still works long definevar i
. i'm not sure if$('#p_scents p').size() + 1;
necessary here.why
return false;
in both 2 functions?
http://jsfiddle.net/jaredwilli/tzpg4/4/
$(function() { var scntdiv = $('#p_scents'); var = $('#p_scents p').size() + 1; $('#addscnt').live('click', function() { $('<p><label for="p_scnts"><input type="text" id="p_scnt" size="20" name="p_scnt_' + +'" value="" placeholder="input value" /></label> <a href="#" id="remscnt">remove</a></p>').appendto(scntdiv); i++; return false; }); $('#remscnt').live('click', function() { if( > 2 ) { $(this).parents('p').remove(); i--; } return false; }); });
var = $('#p_scents p').size() + 1;
above code must have made sense if using var
i
give unique id dynamically added contents ,since id's should unique (then need change selector of size() too).
explanation :
size()
returns how many #p_scents p
(selector)
have in page (say 1)
now adding 1
var i
becomes 2
new input type text added assigned unique name "p_scnt_' + +'"
i.e. p_scnt_2
.
so telling dom should have unique id , therefore should use var i
value give unique id .
like this
$('<p><label for="p_scnts"><input type="text" id="p_scnt_' + +'" size="20" ...
in code have used i
variable give unique name
.
about return false;
, not @ required there since there nothing in code dont want follow after click
event. can use return false
in onclick event stop browser processing rest of execution stack, includes following link in href attribute.
adding , dont need check if( > 2 ) {
in remove button click
because value greater 2
every remove button on page. since @ time of adding remove button dynamically increment var i
value 2
Comments
Post a Comment