开发者

Starts with Selector with $(this) target

I've got a set of form fields based on output from a database. When the page is loaded the fields are populated with the value from the database.

Basically what I want to do is control the .show() .hide() of the div's based on the inputs value. If it's greater > 0 than the div should show.

Each input has a class "event" so I'm using the Starts With Selec开发者_如何学编程tor to target the inputs and handle the if() statement, however I'm running into problems on the targeting of the individual elements after that fact.

            if ($('input[class^="event"]').val() > 0) {
                $(this).parent().show();
            }

My basic ($('input[class^="event"]').val() > 0) works if I put an alert(); on it, but as I said, the targeting of the elements after that isn't work for me.

EDIT - As Requested, the HTML

<div class="formbox Open sept25_morning"><input name="newsletter" value='#POPULATED_FROM_DB' class="event"/><strong>Good 'ol Hockey Game<br />
    9:00 am - 11:00 am</strong><br />&nbsp;</div>

<div class="formbox Open sept25_morning"><input name="newsletter" value='#POPULATED_FROM_DB' class="event"/><strong>Event #2<br />
    9:00 am - 11:00 am</strong><br />&nbsp;</div>  


It really depends what context you are running your if statement, you could try something like this if it is on page load:

$('input[class^="event"]').each(function() {
    if($(this).val() > 0) {
        $(this).parent().show();
    }
});

Example here


If I understand your question correctly, you want to select all the inputs with a class which starts with "event" and then show their parent class if the value is greater than zero?

You could use .each like in Scoobler's answer, or .filter like below:

$('input[class^="event"]')
    .filter(function () {
        return $(this).val() > 0;
    })
    .parent()
    .show()
;


You can do:

$("input.event").each(function(){
    if ($(this).val()> 0) {
        $(this).closest("div").show();
    }
});


The val method will only return the value of the first input. To check every single input, you'll have to use an each loop:

$('input[class^="event"]').each(function () {
    var $this = $(this);
    if ($this.val() > 0) {
        $this.parent().show();
    }
});

Also, for what it's worth, I could have sworn there was a jQuery selector based on an input's value, but I couldn't find anything like that in the docs. There's probably a plugin or something.

EDIT

Also, based on your HTML, it doesn't look like you need that complicated selector. You could probably just use input.event or something.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜