Unable to call `change` event for cloned `select` control - javascript

I have dynamically added new row by clone the last row, this row contains select picker control.
How can I create the change event for newly added control.
I have tried by adding below script, but it does not work:
console.log($('#${field_uid}-resourcetypepicker-new_' + u).attr('value')); //prints value correctly.
//below event is not called.
$('#${field_uid}-resourcetypepicker-new_' + u).change(function() {
console.write('calling fine');
});
Below is the rendered HTML stuff, copied from Firebug:
<select id="customfield_11200-resourcetypepicker-new_3">
<option value="aaa">aaa</option>
<option value="ddd">ddd</option>
<option value="ddd">ddd</option>
</select>
Qhat can be the cause on this? Its IDs are also match in change and select both are customfield_11200-resourcetypepicker-new_3 same.

use on delegated event
$(document).on('change','#${field_uid}-resourcetypepicker-new_' + u,function() {
console.write('calling fine');
});
use closest static parent instead of document... for better performance

Related

How to get the text and value from a dropdown in Javascript

I have a very basic question. I want to select the SELECTED text and dropdown value from the dropdown and show in the alert box.
My attempt:
Dropdown
<p id="test">
Select a draft:
<select id="Select" name="Select">
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
</p>
JS
$("#Select").change(function()
{
alert($(this).val()); // IF THIS WORKS FINE THEN NEXT LINE CODE SHOULD WORK TOO
alert($(this).text()); // WHY THIS SHOWS ALL THE DROPDOWN TEXTS
alert($("#Select option:selected").text()); // THIS JUST WORKS FINE
});
Question 1: What $(this) signifies? If it's signifies selected element then it should show the text also when doing $(this).text(). BUT IT DOESN'T work as expected.
Question 2: If I need to select the value and text of the dropdown is above mentioned is the efficient way to go about it.
Please guide me.
My JSFIDDLE Attempt
In your change event handler, $(this) is the <select> element.
The element represented by $(this) depends on the context where it is used.
It usually is the element which triggered an event (like here), or the element targeted by the iteration of an .each() loop, for example.
When an <option> is selected, the <select> take its selected option value as a value...
It doesn't do it for the text of the selected option.
So that is why the second alert() statement doesn't work.
The keyword this in your example represents the element on which the event triggered. This means the select element. .text() return all text included in the element, so it gives all elements. .val() returns the value of an input, in this case it will return the value of the select, but beware as it does not return more than one value if you set mutiple=true.
Since we now know that .text() returns the text, and this is the input that changed, we can deduct that you'd prefer using .val() to get the value as it may differ from the display text.
alert($(this).find("option:selected").val());
$(this) is used to make the this object a JQuery object which includes some extra functionality.
You can try this if you want to get the selected item value and text:
$(this).find(":selected").val(); // Gets the value of the selected option, if the value attribute in the option element is null it will give you the text
$(this).find(":selected").text(); // Gets the text of the selected option
hi the 'this' part is the raw DOM element from javascript $(this) makes it a jquery object, so you can use jquery. In this case it's the select.
If I need to select the value and text of the dropdown is above mentioned is the efficient way to go about it.
Yes it's fine.
jQuery get specific option tag text
Answer to question 1:
$(this) means that you pass this to the $ function. In other words, you create a jQuery object from the this object. In your context, this refers to the elements matching the #Select selector: your select element.
$(this).text() is working normally because internally it calls innerText on the select tag: which contains the DOM code of your select and innerText contains all the text (not HTML) of the children of the select.
Answer to question 2:
To retreive the label of the selected option: $("#Select option:selected").text()
To retreive the value of the selected option: $("#Select option:selected").val()
You can alter what you already have written by changing this:
alert($(this).val() + $(this).text());
to:
alert($(this).val() + $("option:selected", this).text());
And overall giving you the code you already have.
$("#Select").change(function()
{
alert($(this).val() + $("option:selected", this).text());
alert($("#Select option:selected").text());
});
$(this) is just selecting the identified object that you are choosing to use 'change' on which in this case is the select box.
$("#Select").change(function() binds the function defined after this point to the HTML element <select id="Select" name="Select">. Therefore within that function, $(this) refers to that Select element. The information within that select element is: <option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>. This is why $(this).text() will give you all the options; you're asking for all the text inside that element.
($this).val() gets you the value of the overall select element, which is the text of the currently selected option.
this refers to the context which was used to invoke the function.
When you change the select option, this refers to the whole select dropdown.
If you look below, when I print the value of $(this).val, it gives the function which returns the value of the selected option.
Whereas, when I print the value of $(this).text, it gives the function which gives the whole select dropdown inner text.
To answer your second question, I think $(this).val() is more efficient as by using $(this) will always refer to the context which invokes the function. Thus, you can create modular code using it, by separating the use of anonymous function into a named function and using it for other select dropdown in your site, if you want in the future.
$("#Select").change(function()
{
console.log($(this).val);
console.log($(this).text);
console.log($(this).val()); // IF THIS WORKS FINE THEN NEXT LINE CODE SHOULD WORK TOO
console.log($(this).text()); // WHY THIS SHOWS ALL THE DROPDOWN TEXTS
console.log($("#Select option:selected").text()); // THIS JUST WORKS FINE
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="test">
Select a draft:
<select id="Select" name="Select">
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
</p>

Jquery Click select box option not work on Chrome [duplicate]

I'm having a problem in Chrome with the following:
var items = $("option", obj);
items.each(function(){
$(this).click(function(){
// alert("test");
process($(this).html());
return false;
});
});
The click event doesn't seem to fire in Chrome, but works in Firefox.
I wanna be able to click on a option element from a combo, if I do instead another kind of element, lets say <li> it works fine. Any ideas? Thanks.
I don't believe the click event is valid on options. It is valid, however, on select elements. Give this a try:
$("select#yourSelect").change(function(){
process($(this).children(":selected").html());
});
We can achieve this other way despite of directly calling event with <select>.
JS part:
$("#sort").change(function(){
alert('Selected value: ' + $(this).val());
});
HTML part:
<select id="sort">
<option value="1">View All</option>
<option value="2">Ready for Review</option>
<option value="3">Registration Date</option>
<option value="4">Last Modified</option>
<option value="5">Ranking</option>
<option value="6">Reviewed</option>
</select>
The easy way to change the select, and update it is this.
// BY id
$('#select_element_selector').val('value').change();
another example:
//By tag
$('[name=selectxD]').val('value').change();
another example:
$("#select_element_selector").val('value').trigger('chosen:updated');
I've had simmilar issue. change event was not good for me because i've needed to refresh some data when user clicks on option. After few trials i've got this solution:
$('select').on('click',function(ev){
if(ev.offsetY < 0){
//user click on option
}else{
//dropdown is shown
}
});
I agree that this is very ugly and you should stick with change event where you can, but this solved my problem.
I found that the following worked for me - instead on using on click, use on change e.g.:
jQuery('#element select').on('change', (function() {
//your code here
}));
<select id="myselect">
<option value="0">sometext</option>
<option value="2">Ready for Review</option>
<option value="3">Registration Date</option>
</select>
$('#myselect').change(function() {
if($('#myselect option:selected').val() == 0) {
...
}
else {
...
}
});
Looking for this on 2018.
Click event on option tag, inside a select tag, is not fired on Chrome.
Use change event, and capture the selected option:
$(document).delegate("select", "change", function() {
//capture the option
var $target = $("option:selected",$(this));
});
Be aware that $target may be a collection of objects if the select tag is multiple.
I use a two part solution
Part 1 - Register my click events on the options like I usually would
Part 2 - Detect that the selected item changed, and call the click
handler of the new selected item.
HTML
<select id="sneaky-select">
<option id="select-item-1">Hello</option>
<option id="select-item-2">World</option>
</select>
JS
$("#select-item-1").click(function () { alert('hello') });
$("#select-item-2").click(function () { alert('world') });
$("#sneaky-select").change(function ()
{
$("#sneaky-select option:selected").click();
});
What usually works for me is to first change the value of the dropdown, e.g.
$('#selectorForOption').attr('selected','selected')
and then trigger the a change
$('#selectorForOption').changed()
This way, any javascript that is wired to
Maybe one of the new jquery versions supports the click event on options. It worked for me:
$(document).on("click","select option",function() {
console.log("nice to meet you, console ;-)");
});
UPDATE: A possible usecase could be the following: A user sends a html form and the values are inserted into a database. However one or more values are set by default and you flag this automated entries. You also show the user that his entry is generated automatically, but if he confirm the entry by clicking on the already selected option you change the flag in the database. A rare sue case, but possible...
I know that this code snippet works for recognizing an option click (at least in Chrome and FF). Furthermore, it works if the element wasn't there on DOM load. I usually use this when I input sections of inputs into a single select element and I don't want the section title to be clicked.
$(document).on('click', 'option[value="disableme"]', function(){
$('option[value="disableme"]').prop("selected", false);
});
Since $(this) isn't correct anymore with ES6 arrow function which don't have have the same this than function() {}, you shouldn't use $( this ) if you use ES6 syntax.
Besides according to the official jQuery's anwser, there's a simpler way to do that what the top answer says.
The best way to get the html of a selected option is to use
$('#yourSelect option:selected').html();
You can replace html() by text() or anything else you want (but html() was in the original question).
Just add the event listener change, with the jQuery's shorthand method change(), to trigger your code when the selected option change.
$ ('#yourSelect' ).change(() => {
process($('#yourSelect option:selected').html());
});
If you just want to know the value of the option:selected (the option that the user has chosen) you can just use $('#yourSelect').val()
Workaround:
$('#select_id').on('change', (function() {
$(this).children(':selected').trigger('click');
}));

Javascript/jQuery Adding Elements to Form and binding events

I'm trying to create a dynamic form, which would have drop-down items which when changed would generate certain input fields. the form is to have at least 1 drop-down on load.
The problem I am facing is that I would need to add a maximum of 4 drop-down items, which would generate the same fields. I can generate the drop-down elements, but I am finding it hard to understand where and how should I plug in my event handler so that the generated elements can use them as soon as they generate.
I have a standard event handling function such as below to handle the default which would get the selected value and would call respective methods to generate the form.
<select id="question-type-1">
..
<option value="text">Text Field</option>
..
</select>
// dummy code -- please see jsfiddle link below
$("#question-type-1").on("change", function(){
....
generateTextField();
....
});
This bit works fine ^
http://jsfiddle.net/fatgamer85/f8QWc/2/
I am trying to add a maximum of 4 select options; and I would like each of them linked to a common event handler? and generate form
<select id="question-type-1">
..
<option value="text">Text Field</option>
..
</select>
<!-- Generated by JS --->
<select id="question-type-2">
..
<option value="text">Text Field</option>
..
</select>
<!-- Generated by JS --->
// dummy code -- please see jsfiddle link below
$("#question-type-1").on("change", function(){
....
generateTextField();
....
});
// Do I manually write 4 different event handling code?
Any ideas would be much appreciated.
The id selector is used to specify a single, unique element. The class selector is used to specify a group of elements. Make use of class selector.
<select class="question-type">
..
<option value="text">Text Field</option>
..
</select>
<!-- Generated by JS --->
<select class="question-type">
..
<option value="text">Text Field</option>
..
</select>
and
$(document).on("change",".question-type", function(){
....
generateTextField();
....
});
You should use event delegation
$(".questions-list").on("change", ".question-type", function(){
....
generateTextField();
....
});
Now for every new select you have same event handler.
Check the fiddle http://jsfiddle.net/f8QWc/5/ Now the problem is elements added from other selects replaces this added earlier. I'm not sure how it should work?
I have created you this script and showed how it should look like. Take a good look at the global_id counter, and the use of html. I didn't initialize the first fieldset cause you can do it yourself very well. I did create only the things your script had trouble with.
http://jsfiddle.net/f8QWc/9/
$(document).ready(function(){
// Configuration
var max_fieldsets = 4;
// Fieldset adding function
var global_id = 1;
function create_fieldset(parent, id)
{
$(parent).append(
"<fieldset class=\"fieldset fieldset-"+ id +"\">" + $("#prototype").html() +
"</fieldset>");
}
// Dropdown behaviour controller
$("#add").on("click", function(){
if(global_id > 4) return; // More than 4 added?
var handle = create_fieldset("body", global_id);
$(".fieldset-"+global_id).children('select').on("click", function() { // Dropdown actions below:
switch($(this).find(":selected").text())
{
case "Checkbox":
alert("add checkbox"); // Replace it with ur code
$(this).val(0); // Reset dropdown
break;
}
});
global_id++;
});
});

How to make the "change event" work on a select drop-down menu when using .attr()

I have the select drop-down menu below:
<select id="select-param-num">
<option value='0'>0</option>
<option value='1'>1</option>
<option value='2'>2</option>
</select>
I have the trigger bellow, to update things on my page when the user change the selected option: (I am calling that first)
$('#select-param-num').change(function () {
//update stuff
});
And then in my initialization I am setting the drop-down menu at a specific value like this:
$("select#select-param-num option[value=2]").attr('selected', true);
I was expecting that .change() would have been called, to automatically update my page but it doesn't.
Do you have any suggestion to make it happen?
Thanks
Just trigger the event, 3 ways for that:
$('#select-param-num').change(); //same as .trigger('change')
$('#select-param-num').trigger('change'); //same as .change()
$('#select-param-num').triggerHandler('change'); //same as others but just because change event doesn't bubble
Use .triggerHandler to run your event handling code:
$("#select-param-num").triggerHandler('change');
You should also not use .attr to set the value of the dropdown. Do this instead:
$("#select-param-num").val("2");
You can use trigger for that .
$('#select-param-num').trigger('change');
.trigger()
In your select, there's no option with value=6. If you add it, and change a little the code, it works. Have a look here: http://jsfiddle.net/sjJkN/
code
$('#select-param-num').change(function () {
$("select#select-param-num option[value=6]").attr('selected', 'selected');
});

jquery replicate values in to other area

IS there an easy way to replicate values in to other areas
i.e. if i have 2 or 3 select menus or other form fields.
say
<select id=first>
<option>1</option>
<option>2</option>
</select>
<select id=second>
<option>3</option>
<option>4</option>
</select>
<div id=firstvalue></div>
<div id=secondvalue></div>
If i want the divs html to automatically show the values of the select box, Would I have to do a piece of code for change on either component ?
Thanks
Lee
You want one code to work on both? Try this (example on jsFiddle)
$("select").change(function() // retrieve all `select` elements
{
// gets the corresponding `div`
$("div").eq($(this).index())
.html($(this).val()); // sets the html value of the `div` to
// the selected value on the `select` element
});
From jQuery docs:
Selectors
.change()
.eq()
.index()
.val()
If you want the divs to automatically show the selected value of any selectbox you can use the following jQuery:
$('#first').change(function(){
/* target the first selectbox with id #first and bind a change event to it */
$('#firstvalue').html($(this).val());
/* set the html of the div with id #firstvalue to the selected option*/
});
/* the same for the second selectbox */
$('#second').change(function(){
$('#secondvalue').html($(this).val());
});
I would recommend changing your HTML though, so the selectboxes that are being handled have the same class and store their target within a data attribute. Like so:
HTML
<select class="show_val" data-target="#value_1">
<option>1</option>
<option>2</option>
</select>
<div id="value_1"></div>
jQuery
$('.show_val').change(function(){
$($(this).data('target')).html($(this).val());
}
This way you can use the same jQuery event for all selectboxes.
You'd use the change event on the select box via the change or bind functions, and in the event handler you'd call the html or text function to set the text on the relevant div, getting the value of the selected option via val (your option elements don't have value attributes, so val will grab their text instead). In both cases, you look up the elements via the $ (or jQuery) function passing in a CSS selector (e.g., $("#first")) for the first select box.
You could do something like this so you wouldn't have to write code for each select/div:
$('select').change(function() {
$('div[id^="' + this.id + '"]').text($(this).val());
});
JSFiddle Example
You could also check out knockout.js and implement the MVVM (Model-View-View-Model) pattern, if you're using a JavaScript backing object that is bound to the view/page.

Categories