0

Using the below code I append some input elements into the #cls div. But when I try to type inside the input also new input add. I only need new input when I click "click" text. Can anyone help me. Thank you

$('#cls').click(function() {
    var add="<input type="text">"
    $(#cls).append(add);
});
<div id="cls">click</div>
2
  • Given the syntax errors in your code, I don't understand how it works currently at all. Commented Feb 12, 2016 at 9:57
  • do you want new input to append every time you click cls? Commented Feb 12, 2016 at 10:03

4 Answers 4

3

You need to see whether the click actually happened in the div

$('#cls').click(function(e) {
  if ($(e.target).is(this)) { //or !$(e.target).is('input')
    var add = '<input type="text">';
    $(this).append(add);
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="cls">click</div>

Sign up to request clarification or add additional context in comments.

2 Comments

I don't know what OP is trying to achieve, but if you keep on clickinng click it appends new input.
@Arun if($(e.target).is($(this))){ would also work. can you explain why chose this instead of $(this). I guess because if wrap in a jquery object it is more "expensive"?
0

If you user .after() method instead of .append() the textbox would appear outside the #cls div and hence clicking the textbox wouldn't cause adding a new one.

Some code

$('#cls').click(function() {
  var add="<input type='text'>";
  $('#cls').after(add);
});

Try it out

Comments

0

Append your input to parent element:

var clicked= false;
$('#cls').click(function() {
  if(!clicked){
    var add="<input type='text'>";
    $(this).parent().append(add);
    clicked = true;
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='cls'>click</div>

Comments

0

use jQuery's one method. it will register click handler only once.

$('#cls').one("click", function(e) {
    var add = '<input type="text">';
    $(this).append(add);
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.