Select element by passing variable in function - jQuery - javascript

I am trying to select all input fields inside a certain element. I pass this element to a function, but I don't know how to go from there:
$('._save, .btn-success').click(function(){
saveForm($('.dashboard_container'));
});
//This functions has to select all the input fields inside the given element
function saveForm(that) {
var input = $(that, 'input'); //This does not seem to work
input.each(function(){
//Do something
})
}
How to chain a variable and a selector together?

The contextual selector takes the parameters the other way around to what you've used:
function saveForm($that) {
var $input = $('input', $that);
$input.each(function(){
//Do something
})
}
You could also use the find() method as you're passing in a jQuery object:
var $input = $that.find('input');

If you need to find all input field inside some element x then you can use .find(input).
For example:
//This functions has to select all the input fields inside the given element
function saveForm(that) {
var input = $(that).find("input"); //This does not seem to work
input.each(function(){
//Do something
})
}
And you can achieve it without using .find as well (the way you were trying to do)
$('._save, .btn-success').click(function(){
saveForm('.dashboard_container');
});
//This functions has to select all the input fields inside the given element
function saveForm(that) {
var input = $(that + ' input'); //This does not seem to work
input.each(function(){
//Do something
})
}

Related

Unable to pass string in to jquery function

I wish to grab the current value of a search input and then clear the input box on focus, store the string and pass it into a function to re-populate the input box on blur.
$("input#search").bind('focus', function() {
var search_text = document.getElementById('search').value;
$("input#search").val("");
}).bind('blur', function(search_text) {
$("input#search").val(search_text);
});
Currently, this successfully grabs the value on focus and clears the input box, but on blur, it populates the input with [object Object].
Am I correctly passing the string on line 4?
Firstly, don't use bind(). It was deprecated a long time ago. Use on() instead.
With regard to your issue, you can't directly pass a parameter to the anonymous handler function in the manner you're attempting. As it stands your search_text variable will hold the blur event.
To fix this you could store the variable in a data attribute on the #search element itself. Try this:
$("input#search").on('focus', function() {
$(this).data('search-text', this.value).val('');
}).on('blur', function(search_text) {
$(this).val($(this).data('search-text'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="search" value="foo bar" />
Also, the behaviour you're creating here is similar to the placeholder attribute. It may be worth investigating that to see if it meets your needs.
Use .on() of jQuery to register event.
var search_text;
$("input#search").on('focus', function() {
search_text = document.getElementById('search').value;
$("input#search").val("");
});
$("input#search").on('blur', function() {
$("input#search").val(search_text);
});
Alternate could be ,
$("input#search").on('focus', function() {
var search_text = document.getElementById('search').value;
$("input#search").val("");
$(this).on('blur', function() {
$("input#search").val(search_text);
});
});
No. Here is how you would do, declaring the variable before the event listeners so that it's in the scope:
var search_text;
$("input#search").bind('focus', function() {
search_text = document.getElementById('search').value;
$("input#search").val("");
}).bind('blur', function() {
$("input#search").val(search_text);
});
The convention in JavaScript for naming variables in Camel Case, so you would rather use searchText (not that it really matters).

I want to make a parameterized function in javascript in which on button

I want to make a parameterized function in javascript
in which on button click an HTML <label> tag should be append with unique id every time I click on button with a parameter value.
If I understood your question, you are trying to bind a click event to a <label> tag. So just find it on the dom
var myLabel = document.getElementById('--your label id--');
And then call
myLabel.addEventListener('click', function() {
// your code goes here
console.log('hey there!');
});
If you happen to be using jQuery, you can use a cleanner syntax:
$('#label').on('click', function () {
// you can even fetch data from the label:
var title = $(this).attr('title');
var customData = $(this).data('customData');
/* ... */
});

Find All the controls in a form using jQuery or javascript

I am a starter in jQuery . How to find all the controls in a form using jQuery?
I know the code is like this
function submitValidator(){
$("form :input").each(function(){ });
I want to access their Id's and need to apply regular expressions
Some of the text boxes are numeric remaining will be alphanumeric. Is there any method to sort them to apply regular expressions?
You can add a new property data-charSet in HTML
<input type="text" id='amt' data-charSet='numeric'>
add which all controlles you want to add after the "form :"
function submitValidator(){
$("form :text, textarea").each(function(){
var NumericOnly = "^[0-9]*$";
var svId = $(this).attr('id');
if($(this).attr('data-charSet') == 'numericonly')
{
if(!$(this).val().match(NumericOnly)) {
alert("numeric");
eval("$('#" + svId +"').focus();")
return false;
}
}
});
}
It's jQuery, not j-query.
Anyway...
You can do it like this:
$("form :input").each(function (index, element) {
var id = $(this).attr("id"); // returns the object ID
var value = $(this).val(); // returns the object value
// etc
});
use
function submitValidator() {
$("form :input").each(function(){
var id = $(this).attr('id'); // here you got id
});
} // here missed brace
you need not to get Id if you can get object
function submitValidator() {
$("form :input ,form textarea").each(function(){
$(this).yourfunction();
});
}
:input will only give you tags with input, textarea will be missed so need to add that as well
I think you want to do something like this:
$("form").find("input").each(function(){
var currentElementsId = $(this).attr("id");
if(currentElementsId.match(/^regex/)){
//do something
}
});
if you want to get more than only input elements inside the form tag, you can put multiple selectors in the find() function like this; find("input,select,textarea,.className,[type='valueOfAttributeType']") and obviously any other selectors

How to know with jQuery that a "select" input value has been changed?

I know that there is the change event handling in jQuery associated with an input of type select. But I want to know if the user has selected another value in the select element ! So I don't want to run code when the user select a new element in the select but I want to know if the user has selected a different value !
In fact there are two select elements in my form and I want to launch an ajax only when the two select elements has been changed. So how to know that the two elements has been changed ?
You can specifically listen for a change event on your chosen element by setting up a binding in your Javascript file.
That only solves half your problem though. You want to know when a different element has been selected.
You could do this by creating a tracking variable that updates every time the event is fired.
To start with, give your tracking variable a value that'll never appear in the dropdown.
// Hugely contrived! Don't ship to production!
var trackSelect = "I am extremely unlikely to be present";
Then, you'll need to set up a function to handle the change event.
Something as simple as:-
var checkChange = function() {
// If current value different from last tracked value
if ( trackSelect != $('#yourDD').val() )
{
// Do work associated with an actual change!
}
// Record current value in tracking variable
trackSelect = $('#yourDD').val();
}
Finally, you'll need to wire the event up in document.ready.
$(document).ready(function () {
$('#yourDD').bind('change', function (e) { checkChange() });
});
First of all you may use select event handler (to set values for some flags). This is how it works:
$('#select').change(function () {
alert($(this).val());
});​
Demo: http://jsfiddle.net/dXmsD/
Or you may store the original value somewhere and then check it:
$(document).ready(function () {
var val = $('#select').val();
...
// in some event handler
if ($('#select').val() != val) ...
...
});
First you need to store previous value of the selected option, then you should check if new selected value is different than stored value.
Check out the sample!
$(document).ready(function() {
var lastValue, selectedValue;
$('#select').change(function() {
selectedValue = $(this).find(':selected').val();
if(selectedValue == lastValue) {
alert('the value is the same');
}
else {
alert('the value has changed');
lastValue = selectedValue;
}
});
});​
You can save the value on page load in some hidden field.
like
$(document).ready(function(){
$('hiddenFieldId').val($('selectBoxId').val());
then on change you can grab the value of select:
});
$('selectBoxId').change(function(){
var valChng = $(this).val();
// now match the value with hidden field
if(valChng == $('hiddenFieldId').val()){
}
});
$("select").change(function () {
var str = "";
$("select option:selected").each(function () {
str += $(this).text() + " ";
});
$("div").text(str);
})
.change();
http://docs.jquery.com/Events/change

Is there an easier way to reference the source element for an event?

I'm new to the whole JavaScript and jQuery coding but I'm currently doing this is my HTML:
<a id="tog_table0"
href="javascript:toggle_table('#tog_table0', '#hideable_table0');">show</a>
And then I have some slightly ponderous code to tweak the element:
function toggle_table(button_id, table_id) {
// Find the elements we need
var table = $(table_id);
var button = $(button_id);
// Toggle the table
table.slideToggle("slow", function () {
if ($(this).is(":hidden"))
{
button.text("show");
} else {
button.text("hide");
}
});
}
I'm mainly wondering if there is a neater way to reference the source element rather than having to pass two IDs down to my function?
Use 'this' inside the event. Typically in jQuery this refers to the element that invoked the handler.
Also try and avoid inline script event handlers in tags. it is better to hook those events up in document ready.
NB The code below assumes the element invoking the handler (the link) is inside the table so it can traverse to it using closest. This may not be the case and you may need to use one of the other traversing options depending on your markup.
$(function(){
$('#tog_table0').click( toggle_table )
});
function toggle_table() {
//this refers to the element clicked
var $el = $(this);
// get the table - assuming the element is inside the table
var $table = $el.closest('table');
// Toggle the table
$table.slideToggle("slow", function () {
$el.is(":hidden") ? $el.text("show") : $el.text("hide");
}
}
You can do this:
show
and change your javascript to this:
$('a.tableHider').click(function() {
var table = $(this.name); // this refers to the link which was clicked
var button = $(this);
table.slideToggle("slow", function() {
if ($(this).is(':hidden')) { // this refers to the element being animated
button.html('show');
}
else {
button.html('hide');
}
});
return false;
});
edit: changed script to use the name attribute and added a return false to the click handler.
I'm sure this doesn't answer your question, but there's a nifty plugin for expanding table rows, might be useful to check it out:
http://www.jankoatwarpspeed.com/post/2009/07/20/Expand-table-rows-with-jQuery-jExpand-plugin.aspx

Categories

Resources