Selected value on a cloned item not working as expected - javascript

Fiddle is here, containing this code: http://jsfiddle.net/enp2T/6/
<select id="aList">
<option value="0">0</option>
<option value="100">100</option>
<option value="200">200</option>
<option value="300">300</option>
</select>
<div id="newListContainer"></div>
$(function() {
var value = 300;
var clonedList = $('#aList').clone();
var listHtml = clonedList
.removeAttr('id')
.val(value)
.wrap('<div/>')
.parent()
.html();
$('#newListContainer').html(listHtml);
//$('#newListContainer>select').val(value);
});
I thought that my selected value of 300 would be maintained, but listHtml just contains a clone of the original list. I'm in a situation where it would be painful to try to re-find the object and set its value after it gets drawn (passing it to another external libraries function defers rendering till later, no complete callback unless I modify that library directly which I'm trying to avoid).
So am I doing something horribly wrong? Missing a quirk?
Clarification: I need to pass the HTML as a string, as the library that is using it is expecting a string.

There's no reason to make a round-trip to markup for this, and I suspect that's the problem, as jQuery's val sets the selectedIndex of the select element, which doesn't get serialized.
Just use the cloned element:
var wrappedList = clonedList
.removeAttr('id')
.val(value)
.wrap('<div/>')
.parent();
// Note: Not doing `.html()` at the end
// html(...) would empty the container and then add the HTML, so
// we empty the container and then append the wrapped, cloned list
$('#newListContainer').empty().append(wrappedList);
Updated working fiddle

jQuery clones the list with whatever you have selected - the problem here is that you don't have anything selected, so you're cloning a dropdown without a selected value (see here).
For an updated version of that script, check this updated jsFiddle.
Code:
$(function() {
var value = 300;
var clonedList = $('#aList').clone();
clonedList.find('option[value="' + value + '"]').attr('selected', 'selected');
var listHtml = clonedList
.removeAttr('id')
.val(value)
.wrap('<div/>')
.parent()
.html();
$('#newListContainer').html(listHtml);
//$('#newListContainer>select').val(value);
});

See this link. You can't set value to the select, you must set selected attribute to item with value=300.
$(function() {
var value = 300;
var clonedList = $('#aList').clone();
clonedList.find('option[value="' + value + '"]').attr("selected", true);
var listHtml = clonedList
.removeAttr('id')
//.val(value)
.wrap('<div/>')
.parent()
.html();
$('#newListContainer').html(listHtml);
//$('#newListContainer>select').val(value);
});
I have a mistake. #T.J. Crowder is right. jQuery can set value of select by .val(value) function. link
$(function() {
var value = 300;
var clonedList = $('#aList').clone();
var holderCloned = clonedList.removeAttr('id').val(value).wrap('<div/>').parent();
$('#newListContainer').empty().append(holderCloned);
});

Related

Filling a select box of a form using the text inside the <option> tags with CasperJS

I would like to fill the "Acheter un billet" form of this site : http://www.leguichet.fr/
This is what I've done so far :
var casper = require('casper').create();
casper.start('http://www.leguichet.fr/', function() {
this.fill('form#search_tickets', {'departure':'1', 'arrival':'2'}, false);
this.click('input[value="Rechercher"]');
this.wait(1000, function() {
this.echo(this.getCurrentUrl());
});
});
casper.run(function(){
this.exit();
});
The documentation says that fill() uses the value attribute to match against but I would like to use the text inside the option tags. For instance they have :
<option value="Montpellier">Montpellier</option>
<option value="Montpellier">Béziers</option>
Thus if I want to select Béziers I have to write 'departure':'Montpellier'.
Is there a way to use the text inside the option tags?
The easiest way would be to retrieve the element value of the option that you want to select and use that value later. It may be the case that during the subsequent selection another option is selected, but the value will be the same, so it should not make a difference:
var x = require('casper').selectXPath;
casper.start('http://www.leguichet.fr/', function() {
var textToSelect = "Béziers";
var value = this.getElementAttribute(x("//form[#id='search_tickets']//select[#name='departure']/option[contains(text(), '" + text + "')]"), 'value');
this.fill('form#search_tickets', {'departure': value, 'arrival':'2'}, false);
this.click('input[value="Rechercher"]');
this.wait(1000, function() {
this.echo(this.getCurrentUrl())
});
});
You can easily select DOM nodes with XPath by testing their text content with the text() function. Do the same thing for arrival.

document.getElementById("id") vs $("#id")

if iam getting value of x and y by document method than its ok but if i get value of x and y by directly as below which is commented out by me than i get error why this is so?
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
</head>
<body>
Select a fruit and click the button:
<select id="mySelect">
<option value="11">Apple</option>
<option value="12">Orange</option>
<option value="13">Pineapple</option>
<option value="14">Banana</option>
</select>
<button type="button" onclick="myFunction()">Display index</button>
<script>
function myFunction() {
var x = document.getElementById("mySelect").selectedIndex;
var y = document.getElementById("mySelect").options;
//var x = $("#mySelect").selectedIndex;
//var y = $("#mySelect").options;
alert("Index: " + y[x].index + " text is " + y[x].text + " and value is " + y[x].value);
}
</script>
</body>
</html>
i get error why this is so
Because the object returned by the jQuery constructor doesn't have selectedIndex or options properties.
$('selector') creates a jQuery collection out of matches in the DOM whereas document.getElementId('selector') is a reference to a specific DOM element.
$('selector') contains a reference to the DOM element, but doesn't have DOM element properties/methods, instead it has jQuery methods.
To use DOM element properties/methods, you can 'get' the DOM element from the jQuery collection using square bracket notation, since our jQuery collection is an array-like object:
var x = $("#mySelect")[0].selectedIndex;
var y = $("#mySelect")[0].options;
Or, using .get():
var x = $("#mySelect").get(0).selectedIndex;
var y = $("#mySelect").get(0).options;
Or, return a property value using .prop():
var x = $("#mySelect").prop('selectedIndex');
var y = $("#mySelect").prop('options');
For document.getElementById(“id”) vs $(“#id”) see this question
var x = $("#mySelect").selectedIndex;
var y = $("#mySelect").options;
selectedIndex and options are undefined. You should use .text() and .val()
Solution for your snippet
$('#btn').on('click', function() {
// var x = document.getElementById("mySelect").selectedIndex;
// var y = document.getElementById("mySelect").options;
var x = $("#mySelect").val();
var y = $("#mySelect option:selected").text();
alert(x + " :: " + y);
//alert("Index: " + y[x].index + " text is " + y[x].text + " and value is " + y[x].value);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Select a fruit and click the button:
<select id="mySelect">
<option value="11">Apple</option>
<option value="12">Orange</option>
<option value="13">Pineapple</option>
<option value="14">Banana</option>
</select>
<button type="button" id="btn">Display index</button>
the fiddle
Those methods dont live on the jQuery object, you can console.log the object and see what they inherit through their prototype chain.
From MDN:
Summary Returns a reference to the element by its ID.
Syntax element = document.getElementById(id); where
element is a reference to an Element object, or null if an element
with the specified ID is not in the document.
The important part to take away is the reference to the Element object.
Here you can see the methods that are available from this object.
$() is a jQuery Object Constructor, it will make a jQuery object and wrap the selected elements inside this object (all DOM properties can still be accesed but not directly).
getElementById() is a native javascript function that retrieves the DOM element which has its normal properties.
You usually don't need to access the DOM element within the jQuery Object as you can use the jQuery methods living inside the Object that will manipulate the selected elements. It's a little bit tricky with selects as I don't see any methods just to retrieve the options list however:
$('#select option'); //Selects all the options of the select
$('#select option').each(function(){
//iterate all options of the select.
});
$('#select option:selected'); //Get the selected option.
Would be fair equivalent. From then on you can use jQuery methods to manipulate the options, for example:
$('#select option:selected').text(); //Option text
$('#select option:selected').val(); //Value of option
$("...") returns a jQuery collection that contains the matched elements. You cannot access the elements and their properties directly, instead:
Use the jQuery.get accessor method:
var x = $("#mySelect").get(0).selectedIndex;
var y = $("#mySelect").get(0).options;
Dereference the element:
var x = $("#mySelect")[0].selectedIndex;
var y = $("#mySelect")[0].options;
Use jQuery.prop:
var x = $("#mySelect").prop("selectedIndex");
var y = $("#mySelect").prop("options");
Having said all that, you can change your code to this:
var $selectedOption = $("#mySelect option:selected");
console.log(
$selectedOption.index(),
$selectedOption.text(),
$selectedOption.val()
);
$("#element"); is a jquery css-syntax-like DOM selector gathering all matching results in an array of jQuery objects which can access the full scale of jQuery functions which are very handy and easy to use out of the box.
while "doucment.getElementById("element);" is a native JavaScript function.
JQuery is an abstraction layer for JavaScript with an easier syntax, powerful tools/functions out of the box and is also fixing browser compatiblity issues for you.
Short to say it executes JavaScript for you in the background you do not have to bother with.
You should try to get used to code jQuery whenever possible as it makes your life easier and you dont have to bother with complex and tons of lins of code with only small effect such as for example: writing a AJAX request natively in JavaScript is like 15 more lins of code compared to jQuery with the total same effect.
Some examples that do exactly the same thing:
Access element
JavaScript:
alert(document.getElementById("element").name);
JQuery:
alert($("#element").attr("name"));
Loop elements
JavaScript:
var elements = document.getElementsByClassName("class");
for(var i = 0; i < elements.length; i++) {
alert(var element = elements[i].name);
}
JQuery:
$(".class").each(function() {
alert($(this).attr("name")); //This accesses the current element of each function as a full useable and handy object
});
This are only two examples and you can see that it is indeed very powerful.
Small code doing exactly the same as big code in plain JavaSCript.
When you are including jQUery you should always try to use its full potential.
--
Your code in JQuery style:
<button id="btn_display_index" type="button">Display index</button>
<script type="text/javascript">
//Will be executed any time the button with id "btn_display_index" is clicked!
$("#btn_display_index").on("click", function() {
var currentOption = $("#mySelect option:selected");
alert("Index: " + currentOption.attr("value") + " - Value: " + currentOption.html());
});
</script>

jQuery onChange prop a value to inputs

I have a <select> drop down that I'm inserting into my HTML via jQuery. I don't have control over the HTML but I do have control over the JavaScript.
I'm trying to prop a value to an <input> element when you select an option. Basically, I have a <select> element with <option id="1"> and <option id="2"> onChange of this <select> element;
If you select option#1 it should prop the value dummy1 to input[name="Check_Config_PaymentGateway_CreditCards_Login1"] and the value dummy2 to input[name="Check_Config_PaymentGateway_CreditCards_Password"]
If you select option#2 it should prop the value dummy3 to input[name="Check_Config_PaymentGateway_CreditCards_Login1"] and the value dummy4 to input[name="Check_Config_PaymentGateway_CreditCards_Password"]
I've been working on this jsFiddle.
I'm pretty new at JavaScript in general, let alone jQuery. This is way to sophisticated for my skill... If you can help me, I'd really appreciate it.
Here you go: http://jsfiddle.net/VW9N6/6/
This binds to the change event of the <select> element to detect when its value changes, and then updates the value of the <input> elements.
Try something like below,
Edit: Cached input text boxes.
DEMO
var dummyValues = [['dummy1', 'dummy2'], ['dummy3', 'dummy4']];
var $loginInput = $('input[name=Check_Config_PaymentGateway_CreditCards_Login1]');
var $pwdInput = $('input[name=Check_Config_PaymentGateway_CreditCards_Password]');
$('#paymentDD').change(function () {
var selectedVal = parseInt($(this).val(), 10) - 1;
$loginInput.val(dummyValues [selectedVal][0]);
$pwdInput.val(dummyValues [selectedVal][1]);
});
Updated dummyValues var as you add move options to the drop down.
I'm a fan of caching elements whenever possible, so that's what I do. I also saw that you were using the latest jQuery (1.7.2) in your jsFiddle, so why not use the recommended .on() method and then call an immediate .change() to populate on load?
You could try something like this:
var $span = $('span#print_pagename'),
$login = $('input[name="Check_Config_PaymentGateway_CreditCards_Login1"]'),
$password = $('input[name="Check_Config_PaymentGateway_CreditCards_Password"]'),
$select = $('<select><option id="1">1</option><option id="2">2</option></select>');
$span.after($select);
$select.on('change', function() {
var $this = $(this);
if ($this.val() === '1') {
$login.val('dummy1');
$password.val('dummy2');
} else if ($this.val() === '2') {
$login.val('dummy3');
$password.val('dummy4');
}
}).change();

How to get Dropdown selected value on client side onchange event?

I have written a code for dropdown selected index changed event at client side using onchange event and create one JavaScript function.
Now, I want to retrieve selected values in this function. How can I get this value?
$("#DropDownlist:selected").val();
This will give you selected text.
$("#mydropdownid option:selected").text();
This will give you selected value
$('#mydropdownid').val();
HTML :
<select id="mySelect" class="myClass">
<option value='1'>One</option>
</select>
jQuery :
Now for getting selected value you can use the one of the following:
ONE :
var selected_value = $("#mySelect").val();
TWO :
var selected_value = $(".myClass").val();
THREE :
var dropdown = $("#mySelect option:selected");
var selected_value = dropdown.val();
The simplest, inside the event handler:
$('#elementID').change(function(event) {
event.target.value;
};
event is the event object sent to the handler, target is the object in the DOM from which the event generated, and value it's the DOM element current value. In the case of a select box this will work perfectly to get your selected value.
As you have tagged jQuery, I assume that's what you are using.
Simply use jQuery val()
var v = $("#yourSelectID").val();
alert("The value is: " + v);
You should also be able to use plain javascript:
var e = document.getElementById("yourSelectID");
var v = e.options[e.selectedIndex].value;
alert("The value is: " + v);

How to get previuos item of Dropdown using jquery or javascript

I want to get the previously selected value of a dropdown control using jquery or javascript.
How can i get this?
I tried with prev() selector of jquery but failed
$(ddlStatus).find("option").prev(":selected").attr("text");
if ddlStatus has items like A,B,C,D,E When the page loads B is selected but when user changes the item {let's say) E then I want previously selected i.e B.
Whenever a selection is made, save the value. On a new selection, you will then have the old value saved until you overwrite it.
You cannot do this dorectly, as you are after historical information - prev is about the ordering not the timing.
You could do it like this (not optimized but works):
$(document).ready(function(){
$(ddl).data('lastSelected', $(ddl).val());
});
$(ddlstatus).change(function(){
var lastSelected = $(this).data('lastSelected');
$(this).data('prevLastSelected', lastSelected);
$(this).data('lastSelected', $(this).val());
});
Then, to know the previously selected anytime, you just do:
var previouslySelectedValue = $(ddl).data('prevLastSelected');
What's good about this code is that the state is saved in the element and you don't use global vars, so it can be applied to any number of select boxes
Hope this helps. Cheers
here is a example:
HTML:
<select id="myselect">
<option value="one" selected="selected">one</option>
<option value="two">two</option>
<option value="three">three</option>
</select>
JQUERY:
var prev = null; //global
var cur = $('#myselect').val();//global
var flag = true;// global
$('#myselect').change(function() {
if (flag) {
prev = cur;
cur = $(this).val();
flag = false;
} else {
prev = cur;
cur = $(this).val();
}
});

Categories

Resources