开发者

jQuery selector on dynamic input value

开发者 https://www.devze.com 2023-03-14 00:01 出处:网络
How can you use the :contain() on an input field, e.g. #inputfield contains开发者_开发百科 a dynamic value of 5.938 and I want to use $(\"#inputfield:contains(\'5.938\')\").

How can you use the :contain() on an input field, e.g.

#inputfield contains开发者_开发百科 a dynamic value of 5.938 and I want to use $("#inputfield:contains('5.938')").

But that won't work, I've provided a demo at jsFiddle.

I don't want to use if(element.val() == '5.938') because I need a provisional selector instead doing an if/else statement.

I also don't mean by using [value=5.938] because the value will change.


Due to @Neal's answer, you need to use some sort of conditional. A simple selector won't work. .filter() will suffice, however:

$('#inputfield').filter(function ()
{
    return $(this).val() == '5.938';
});

That said, it looks like you're using an ID selector, which can select at most one element, so .filter() is overkill — if...else really makes the most sense in that case.


This should work:

$("#inputfield:text[value*='"+dynamicValue+"']").length

//will select text input #inputfield with a value containing dynamicValue.

jsfiddle: http://jsfiddle.net/XEP4c/3/


The answers here seem to get confusing as there isn't a clear explanation. When you set the value dynamically like:

$('#inputfield').val('5.938')

It does not work to get the value using the selectors like:

$('#inputfield[value="5.938"]')

There are a few workarounds for this. One is to use a filter:

var inputfield = $('#inputfield').filter(function () {
    return $(this).val() == '5.938';
});
if (inputfield.length) {
    alert("The input field has the value 5.938");
}

Or you could create your own selector:

(function($) {
    $.extend($.expr[':'], {
         val: function(el, i, attr) {
               return $(el).val() === attr[3];
         }
    });
}(jQuery));
if ($('#inputfield:val("5.938")').length) {
    alert("The input field has the value 5.938");
}


Manji's answer is simpler than the selected answer, although a simpler form again. I couldn't get this to work for me:

$("input[value='userID']").remove();

Concatenating the string to insert the dynamic variable works a treat instead though:

$("input[value='" + userID + "']").remove();

Obviously replace the .remove() with whatever you want to do with it.


You want to use the attribute selector:

$('#inputfield[value='+dynamicValue+']')
0

精彩评论

暂无评论...
验证码 换一张
取 消