开发者

Javascript loop with dynamic jquery val() not being picked up

I'm trying to pick out the value of an input box using jquery. No probs there

$('#id_of_my_input_box_1').val();

But I need several so decided to put them into a loop:

============

var config_total_instances = '==some value='

for (var x = 1; x <= config_total_instances; x++) {

    if (isset($('#id_of_my_input_box_'+x).val())) {

        alert($('#id_of_my_input_box_'+x).val());

    }

}

============

If I submit the form and I've got s开发者_JAVA百科ay 10 input boxes, the code above doesn't alert a value if the relevant input box has value. I'm using a function below to check for values.

============

function isset(my_variable) {

    if (my_variable == null || my_variable == '' || my_variable == undefined)

        return false;
    else
        return true;
}

============

Am I missing something vital..? :-(

Addition: I shoudl add that I'm askign why I don't get the value of $('#id_of_my_input_box_'+x).val() echoed out in my alert box


Extending @Faber75's answer. You can set a class name for all your text element and then use something like this

$("input:text.clsname").each(function(){
    if (isset(this.value)) {
        alert(this.value);
    }
});

In your current code if you are assigning a string to config_total_instances then it will not work.


don't consider my message an answer, more of a tip. For a simplier code you could consider adding a class to the textboxes you need to check. For example adding to all the inputs you need to check the class="sample" you could the use the jquery selector $(".sample") , returning you all the items and then you could simply do $(".sample").length to count the items and $(".sample")[0].val() (or similar) to get/test values.

Cheers


Have you tried this? (note that there are three =)

if (my_variable === null || my_variable == '' || my_variable === undefined)

As an alternative to this try

if (typeof(my_variable) == 'null' || my_variable == '' || typeof(my_variable) == 'undefined')


Maybe I'm misunderstanding, but can't you just get all the <input>'s in a <form> that aren't :empty if that's the end goal of what you're trying to accomplish?

$('form#some_id input:not(:empty)').each(function () {
     // do something with $(this).val() now that you have
     // all the non-empty <input> boxes?
});

Or if you're just trying to tell if the user left some <input> blank, something like:

$('form#some_id').submit(function (e) {
     if ($(this).find('input[type="radio"]:not(:checked), input[type="text"][value=""], select:not(:selected), textarea:empty').length > 0) {
         e.preventDefault(); // stops the form from posting, do whatever else you want
     }
});

http://api.jquery.com/category/selectors/form-selectors/

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜