Alan2
Alan2

Reputation: 24572

Can I simplify this jQuery where I look for elements on a form?

Is there a way that I can simplify this code:

var topic_html = obj.$form.find("#select-topic").html();
var topic_val = obj.$form.find("#select-topic").val();
var topic_text = obj.$form.find("#select-topic option:selected").text();

I know it's fairly clean but is there a way that I can avoid the three instances of obj.$form.find.

Upvotes: 2

Views: 68

Answers (3)

Matthew Blancarte
Matthew Blancarte

Reputation: 8301

Here's a slight variation to @xdazz's answer. I try to keep it to a single var keyword.

var topic = obj.$form.find("#select-topic"),
    topic_html = topic.html(),
    topic_val = topic.val(),
    topic_text = topic.find("option:selected").text();

Upvotes: 0

Ariel
Ariel

Reputation: 26753

You are getting an object by its id - why are you doing obj.$form.find?

Just do $('#select-topic') - unless you need to make sure the element is a child of the form?

Anyway:

var select = $('#select-topic');
var topic_html = select.html();
var topic_val = select.val();
var topic_text = select.find('option:selected').text();

Why do you need all three versions of the same thing?

Upvotes: 4

xdazz
xdazz

Reputation: 160843

You don't need find the select each time, cache it in a variable.

var topic = obj.$form.find("#select-topic");
var topic_html = topic.html();
var topic_val = topic.val();
var topic_text = topic.find("option:selected").text();

Upvotes: 8

Related Questions