I have some code that grabs the first select on the page and clones it so that I can reset it later on if needed.
mySelect = jQuery('select').get(0);
origSelect = jQuery(mySelect).clone();
jQuery(mySelect).change(function(){
//some code
}
When I fire the code to reset the select with:
jQuery(mySelect).replaceWith(origSelect);
The onChange function stops working. I've determined that it's because it is now referred to as origSelect and responds to onChanges for that name. Do I have any options here for replacing the content of mySelect with the content of origSelect without changing the name it's referred to by?
Pass a parameter true to the clone method.
origSelect = jQuery(mySelect).clone(true); //This will clone the select with data and events
or replace the innerHTMl of origSelect with that of mySelect.
jQuery(origSelect).html(jQuery(mySelect).html());
Use $(mySelect).live('change', ...) instead of $(mySelect).change(...).
Related
I have a html div and I clone it using Jquery. That div contains labels and text fields. ids of all of them generated and assigned dynamically. I have no problem with that.
A java script is assigned to a text field of original div. The cloned text fields does not have the javascript assigned to it.
the script I need to assign:
<script>
$(function() {
$("#datepick_onBooking,#datepick_Pay1,#datepick_Pay2,#datepick_totPay,#datepick_deedFees").datepicker();
});
</script>
the script I use to make clones:
<script>
var i = 3;
//When DOM loaded we attach click event to button
$(document).ready(function() {
$('#addAnotherPayment').click(function() {
var cloned = $('.PayDiv0').first().clone();
var noOfDivs = $('.PayDiv0').length+2;
cloned.insertBefore("#totPayForm");
// append count to the ids
cloned.attr('id', 'PayDiv' + noOfDivs);
cloned.find('label').attr('id', 'PayLbl' + noOfDivs);
cloned.find('input[type="text"]').attr('id', 'datepick_Pay'+ noOfDivs);
cloned.find('input[type="number"]').attr('id', 'amount_Pay'+ noOfDivs);
cloned.find('.PayLbl2').html("Payment No " + i++ + ':');
});
});
</script>
datepick_Pay1, datepick_Pay2, datepick_totPay, datepick_deedFees are static elements and they have been assigned to the script. I create text fields using cloning as datepick_Pay3,datepick_Pay4, and so on.
I cannot figure out how to dynamically assign the script to that newly created elements.How can I do that?
A Boolean indicating whether event handlers and data should be copied along with the elements.
change this line.
var cloned = $('.PayDiv0').first().clone(true);
when you clone something especially elements which having events
use parameter as
clone(true)
But this will be harmfull based on how event is attached on the actual element when copying the events to the cloned element may affect the actual.
You need to clone with events. http://api.jquery.com/clone/
var cloned = $('.PayDiv0').first().clone(true);
Then your script needs to be changed to work for dynamic elements. Here as soon as input elements gets focus, asssign the datepicker based on wild card id selector, if it doesn't already have one.
$(function() {
$('body').on('focus',"input[id^=datepick_]", function(){
if(!$(this).hasClass('.hasdatepicker'))
{
$(this).datepicker();
}
});
});
I have a variable with a jQuery object, for example:
var div = $('#div_element');
How can I manipulate ONLY the div variable, without changing the #div_element itself?
I want to do some edits on the div variable and to pass it as an argument to a plugin, like this:
var el = $('#div');
el.find(':first').remove();
$().popup(el); //I wrote this plugin myself
Actually I want to display popup containing the #div element (with removed the first "child"), but don't want to change the #div element itself.
Use clone to create a copy of the element.
var el = $('#div').clone();
You can use like
$().popup($("#div :not(:first-child)"));
I have a 2 select boxes. The first select box alters the second. The second can have a small set of variable options.
What I have done is when the page loads I save the options as a variable.
var optionList = $('select[name="location"] option');
When the first select box changes. I then do something like below matching the value of the first select box to a switch statement then knocking out and adding new options to select box 2.
case 'add':
$('select[name="location"] option').remove();
$(optionList).each(function() {
$('select[name="location"]').append($(this));
});
$('select[name="location"] option:not(option[value="cart"])').remove();
break;
This all works fine.
What I need to do now is add an option to the optionList. I have tried both append and after. Append adds a new option inside the last option. After causes a jQuery error. Any idea how I do this?
var html = '<option value="'+v+'">'+l+'</label>';
$(optionList).append(html); // Fails
$(optionList).after(html); // jQuery error line 3
Firstly, you are appending an option tag, with a closing label tag, it should be:
var html = '<option value="'+v+'">'+l+'</option>';
Secondly, with the code you have it will append your new option after every existing option (as optionList is an array of all the existing option elements).
Instead you should just append it to the select element, like this:
$('select[name="location"]').append(html);
$('select[name="location"] option'); is selecting the options which are part of that select. So when you do $(optionList).append(html);, you are appending "html" to the each option in that results list.
Personally, I'd typically do something like:
var $mySelect = $('select[name="location"]');
var optionList = $mySelect.find('option');
...
$mySelect.append(html);
but you could also do something like this:
var optionList = $('select[name="location"] option');
...
optionList.filter(':first').parent().append(html);
The second option is less performant though.
optionList.push(html) didn't work because optionList is a jQuery-wrapped array of options (each one a jQuery-wrapped option), not a select's list of options within document.forms.
optionList.push($(html)) worked beause you wrapped the raw DOM element "html" with jQuery, and thus you were just adding another jQuery-wrapped option to optionList. You could save a character (and be a bit more jQueryish) if you instead did optionList.add($(html)). However, either of those would only add the "html" element to the optionList collection; it wouldn't actually add "html" to the DOM.
Last, two side notes... First, appending like you're doing in that loop is a really bad idea; you're hitting the DOM, and also triggering a repaint, on each time through the loop. You're far better creating an array of options, then doing something like
jQuery.fn.append.apply($('select[name="location"]'), objectArray);
That only does a single hit on the page, and triggers only one repaint. See http://www.learningjquery.com/2009/03/43439-reasons-to-use-append-correctly for more.
Second, $(optionList) is redundant and costs you some performance. optionList is already a jQuery object - ie, $('select[name="location"] option'). $(optionList) invokes the jQuery constructor, only to have it realize that optionList is already a jQuery object, and internally it is then converting your use of $(optionList) into jQuery actually just using optionList.
is it possible to "override/overwrite" an input element fixed value using javascript and/or jquery?
i.e. if i have an input element like this:
<div id="myDiv">
<input type="text" name="inputs" value="someValue" />
</div>
is it possible to make a jquery object of that element and then change its value to something else then rewrite the jquery object to the dom??
I'm trying but obviously I haven't got good results!
I've been trying something like this:
$('input').val("someOtherDynamicValue");
var x = $('input');
$("#myDiv").html(x);
If you just want to manipulate the value of the input element, use the first line of your code. However it will change the value of every input element on the page, so be more specific using the name or the id of the element.
$('input[name=inputs]').val("someOtherDynamicValue");
Or if the element had an id
$('#someId').val('some Value');
Check out jQuery's selectors (http://api.jquery.com/category/selectors/) to see how to get whatever element you need to manipulate with jQuery.
You can directly access the value via the $.val() method:
$("[name='inputs']").val("Foo"); // sets value to foo
Without needing to re-insert it into the DOM. Note the specificity of my selector [name='inputs'] which is necessary to modify only one input element on the page. If you use your selector input, it will modify all input elements on the page.
Online Demo: http://jsbin.com/imuzo3/edit
//Changes on the load of form
$(document).ready(function(){
$('#yourTxtBoxID').val('newvalue');
});
//Changes on clicking a button
$(document).ready(function(){
$('#somebuttonID').click(function(){
$('#yourTxtBoxID').val('newvalue');
});
});
Perhaps I'm using $.data incorrectly.
Assigning the data:
var course_li = sprintf('<li class="draggable course">%s</li>', course["fields"]["name"]);
$(course_li).data('pk', course['pk']);
alert(course['pk']); // shows a correct value
alert($(course_li).data('pk')); // shows null. curious...
course_li is later appended to the DOM.
Moving the li to a different ul:
function moveToTerm(item, term) {
item.fadeOut(function() {
item.appendTo(term).fadeIn();
});
}
Trying to access the data later:
$.each($(term).children(".course"), function(index, course) {
var pk = $(course).data('pk');
// pk is undefined
courses.push(pk);
});
What am I doing wrong? I have confirmed that the course li on which I am setting the data is the same as the one on which I am looking for it. (Unless I'm messing that up by calling appendTo() on it?)
When you store the data:
$(course_li).data('pk', course['pk']);
you're creating an element but not saving it, so it's lost. Your alert test test the wrong value; it should be:
$(course_li).data('pk', course['pk']);
alert($(course_li).data('pk'));
which is null. Consider:
$(course_li);
$(course_li);
This creates two different elements with source equal to course_li, which are then promptly lost. What you need to do is create the element first, then work with that single element (i.e. don't call $(course_li) more than once). For example,
var course_li = $(sprintf('<li class="draggable course">%s</li>',
course["fields"]["name"]));
course_li.data('pk', course['pk']);
parent.append(course_li);
Note that course_li now holds an element, rather than a string.
try checking to see if the element being created by this call:
$(course_li)
is a single 'li' element, or a div. From the doco:
When the HTML is more complex than a single tag without attributes, as it is in the above example... snip ...Specifically, jQuery creates a new <div> element and sets the innerHTML property of the element to the HTML snippet that was passed in
So it's probably creating a div that you are assigning the data to, so when you select the 'li' itself, you are getting a child of the actual element that you set the data on.