最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to check if there exist an input with specific name attr using jQuery - Stack Overflow

programmeradmin3浏览0评论

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?

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?

Share Improve this question asked Oct 29, 2013 at 6:00 rkbrkb 5443 gold badges9 silver badges19 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 9

Check length with equal-selector like,

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

Demo

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

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

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

see in codepen

发布评论

评论列表(0)

  1. 暂无评论