In the code below I have two jQuery selectors that seem to work correctly. Is there a reason to do one instead of the other, or is there another preferred way?
var val1 = $("#username", this.el ).val()
var val2 = $(this.el).find("#username").val();
I'm aware that there should not be multiple elements with the same id, but if there are multiple elements with the same id, what is the best way to select only the element in the view (see example below for username).
<body>
Username: <input type="text" id="username" /><br />
<br /><br />
<div id="login">
Username: <input type="text" id="username" /><br />
<button id="loginButton">Login</button>
</div>
<script type="text/javascript">
var LoginView = Backbone.View.extend({
el: "#login",
events: {
"click #loginButton": "login"
},
login: function () {
var val1 = $("#username", this.el ).val()
var val2 = $(this.el).find("#username").val();
console.log(val1);
console.log(val2);
}
})
var loginView = new LoginView();
</script>
</body>
--------------------- Update ------------------------
I create jsFiddle example so that there could be a working example for other to look at. http://jsfiddle.net/BarDev/9QpKy/
The select() method is an inbuilt method in jQuery which is used when some letters or words are selected (or marked) in a text area or a text field. Syntax: $(selector). select(function);
By default Backbone will use: jQuery, // Zepto, or Ender; but the `setDomLibrary()` method lets you inject an // alternate JavaScript library (or a mock library for testing your views // outside of a browser).
The jQuery #id selector uses the id attribute of an HTML tag to find the specific element. An id should be unique within a page, so you should use the #id selector when you want to find a single, unique element.
The jQuery syntax is tailor-made for selecting HTML elements and performing some action on the element(s). Basic syntax is: $(selector).action() A $ sign to define/access jQuery. A (selector) to "query (or find)" HTML elements. A jQuery action() to be performed on the element(s)
For brevity, I usually use the Backbone-provided shortcut:
this.$('#username')
which is an alias for $('#username', this.el);
However, any selection method you use will work well enough. The other two ways that you've got in your example are good.
First of all I would suggest you not to have multiple elements with same id on a page. Try to avoid that. Coming to find an element, I think find
is better than selecting element passing the context because context is good for performance reason but find
is faster than context
so it is better and also it is more compact and readable.
var val2 = $(this.el).find("#username").val();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With