JQuery go through several/all HTML elements with specific name

问题: Basically I'd like my function to go through all HTML-elements with a specific name and compare each of their value's with a string. I looked through Stackoverflow and ot...

问题:

Basically I'd like my function to go through all HTML-elements with a specific name and compare each of their value's with a string.

I looked through Stackoverflow and other sites for a while, but nothing I found seemed to have worked. So far I tried:

function checkValue(name, value)
{
    $("[name=" + name + "]").each(function () {
        console.log(value);
    });
}

and

function checkValue(name, value)
{
    if ($("[name*=" + name + "]").val() == value) {
        console.log(value);
    }
}

But each gave an Error looking like this:

jquery.min.js:2 Uncaught Error: Syntax error, unrecognized expression: [name=[object HTMLInputElement]]
    at Function.oe.error (jquery.min.js:2)
    at oe.tokenize (jquery.min.js:2)
    at oe.select (jquery.min.js:2)
    at Function.oe [as find] (jquery.min.js:2)
    at w.fn.init.find (jquery.min.js:2)
    at new w.fn.init (jquery.min.js:2)
    at w (jquery.min.js:2)
    at checkValue (index.js:10)
    at include_moduleingabe_function.php:280

EDIT:

Turns out I had both in my code and my function-call some quotation marks missing, which messed it all up. I changed the code to:

function checkValue(name, value)
{
    if ($("[name='" + name + "']").val() == value) {
        console.log(value);
    }
}

This variant doesn't throw an error anymore, though it doesn't seem to be checking each element with that name attribute, but only the first...


回答1:

You could use the attribute starts with, something like this:

var StartsWith;
StartsWith = 'txt';
$('[id^=' + StartsWith + ']').each(function () {
    if (this.value == 'myStringToCompare') {
        alert(this.id);
    }
});
  • 发表于 2019-02-20 11:49
  • 阅读 ( 239 )
  • 分类:sof

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除