2

I need a function to add new input element dynamically using jQuery.

It is something like this

function addInput(inputName) {
  $('<input>', {
    type: "hidden",
    name: "inputName"
  }).appendTo('#foo');
}

addInput('test');

and it works, It adds a new <input type="hidden" name="test"> to #foo

Problem appears when I want to make this function add input only if input with specified name does not exists in DOM.

Here is my updated function

function addInput(inputName) {
  if (! $(input).attr('name','inputName') {
    $('<input>', {
      type: "hidden",
      name: "inputName"
    }).appendTo('#foo')
  }
}

addInput('test');

But insteed checking for input elements with the name test it sets name of all input elements to test. Is there any method to only test input name?

3 Answers 3

9

Check length with equal-selector like,

function addInput(inputName) {
  if (! $('input[name="'+inputName+'"]').length) {
    $('<input>', {
      type: "hidden",
      name: inputName
    }).appendTo('#foo')
  }
}

Demo

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

Comments

2
function addInput(inputName) {
    if ($('input[name="'+inputName+'"]').length > 0)
     {
      alert("Exists");
     }
    }

Comments

1

if you work with jQuery just use .is() function:

if(input.is('[name="your_name"]')){
   //do some things!
}

see in codepen

1 Comment

var input= $('input');

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.