0

I have inherited a piece of code which has a series of functions like the following:

$("#data[User][notify_one_day_out]").change(function () {
    $("#updatenotificationsform").submit();
}

$("#data[User][notify_one_month_out]").change(function () {
    $("#updatenotificationsform").submit();
 }

and this goes on and on. How do I just write one function that does the same thing since every ID begins with data. Sorry am a JS newbie

Thanks

1
  • 1
    Isn't this just the exact same code twice? Als, #data[User][notify_one_day_out] matchs the element with ID data if the User and notify_one_day_out attributes are set. If they are part of the ID instead, you have to escape []. Commented Feb 24, 2012 at 3:09

3 Answers 3

4

Something like this would probably work for you:

$('[id^="data"]').change(function() {
 $("#updatenotificationsform").submit();
}

That basically says: grab all the elements with an Id starting with the string "data", you can read more about that here: http://api.jquery.com/attribute-starts-with-selector/

Let me know if that helps!

Edit

Alternatively if you can modify your mark up, you could assign the same class to all those elements, and then just select using the class selector.

Sign up to request clarification or add additional context in comments.

1 Comment

The alternative solution you offer here is definitely the way to go if you have control over the html output.
0

In addition to @Deleteman's sound advice, remember that you can specify multiple selectors for $(), e.g.:

$(  "#data[User][notify_one_month_out]",
    "#data[User][notify_one_day_out]",
    "#some-other-selector",
    // ...
).change(function () {
  $("#updatenotificationsform").submit();
}

1 Comment

You'd have to escape the [].
0

You can actually stack up those Jquery selectors would that be enough of a help or do you really have ALOT of them?

$("#data[User][notify_one_day_out], #data[User][notify_one_month_out]").change(function ()     
{
    $("#updatenotificationsform").submit();
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.