rkb
rkb

Reputation: 544

How to check if there exist an input with specific name attr using jQuery

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?

Upvotes: 2

Views: 14775

Answers (3)

Rohan Kumar
Rohan Kumar

Reputation: 40639

Check length with equal-selector like,

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

Demo

Upvotes: 9

Mohsen Akbari
Mohsen Akbari

Reputation: 11

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

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

see in codepen

Upvotes: 1

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

Upvotes: 2

Related Questions