jQuery selector on dynamic input value

喜欢而已 提交于 2020-01-06 03:45:10

问题


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.


回答1:


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.




回答2:


This should work:

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

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

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




回答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");
}



回答4:


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.




回答5:


You want to use the attribute selector:

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


来源:https://stackoverflow.com/questions/6413450/jquery-selector-on-dynamic-input-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!