Javascript/jQuery Adding Elements to Form and binding events - javascript

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++;
});
});

Related

Hide text before dollar sign character in options without removing completely

I am trying to find a way to select part of the string before the dollar sign in the select menu. Right now I am just trying to hide it so it does not appear in the dropdown, but it will be used later so I do not want to simply strip it out because I will need to be able to use it in a variable when the option is selected.
var seminiars;
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<select>
<option>1$5,000</option>
<option>2$10,000</option>
<option>5$100,000</option>
<option>10$500,000</option>
</select>
So far I have only been able to remove it completely, but then I was unable to store it and use it when someone selects on of the option.
Side note: I am unable to edit the html directly, the code is automatically generated.
okay... I just noticed the side note.
I am unable to edit the html directly, the code is automatically generated.
The trick here, will be to set a data value for each option.
// Run that loop to set the data values for each option
$("select option").each(function() {
let optionText = $(this).text();
let textSplit = optionText.split("$")
$(this).data("before_dolard_sign", textSplit[0])
$(this).text(textSplit[1])
})
$("select").on("change", function() {
// So on change, you have access to it
console.log($(this).find("option:selected").data("before_dolard_sign"))
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<select>
<option>1$5,000</option>
<option>2$10,000</option>
<option>5$100,000</option>
<option>10$500,000</option>
</select>
You can use the value attribute to store more information not in the text visible to the user. I've added some code below to show how you can get the text or value selected by the user.
If that isn't suitable I've also created a test input and button which helps demonstrate how you can split a string in the way you need to.
The code is fully commented.
Let me know if you were hoping for something else.
// Detect when user changes select option
$("#selectTest").change(function() {
// Get the text selected by the user
console.log($("#selectTest option:selected").text());
// Get the value selected by the user
console.log($(this).val());
});
// Add click event
$("#splitButton").click(function() {
// Get input value
var test = $("#splitTest").val();
// Split around dollar sign
var els = test.split("$");
// Print values to show we did it correctly
console.log(els[0]);
console.log("$" + els[1]);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<select id="selectTest">
<option value="1$5,000">$5,000</option>
<option value="1$5,000">$10,000</option>
<option value="5$100,000">$100,000</option>
<option value="10$500,000">$500,000</option>
</select>
<input id="splitTest" value="10$500,000">
<button id="splitButton">Show Split</button>
why not place this data onto a data-meta attribute?
instead of
<option>1$5,000</option>
<option>2$10,000</option>
<option>5$100,000</option>
<option>10$500,000</option>
perhaps
<option data-meta="1">$5,000</option>
<option data-meta="2">$10,000</option>
<option data-meta="5">$100,000</option>
<option data-meta="10">$500,000</option>
then you can find the selected option and use element.getAttribute("data-meta") to retrieve the data when you need it
edit: i now see your side-note that you can't edit the html. well, replace it. loop over the html, and use .split on the textContent, and move that meta data into an attribute
Use the data attribute to store the info and then run an event listener to retrieve the dataset when selected on change?
const select = document.querySelectorAll('#money');
select.forEach((val) => {
if (val.value != 'undefined') {
val.addEventListener('change', () => {
let data = val.options[val.selectedIndex].dataset['num'];
console.log(data)
})
}
});
<select id="money">
<option style="display: none;">-->Select an option below<--</option>
<option data-num='1' class='opt' value='5000'>$5,000</option>
<option data-num='2' class='opt' value='10000'>$10,000</option>
<option data-num='5' class='opt' value='100000'>$100,000</option>
<option data-num='10' class='opt' value='500000'>$500,000</option>
</select>

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');
}));

Using multiple div id's with same piece of script

I have several select boxes on a page, and basically anytime an onchange event occurs with any of those boxes I want to use the same piece of code instead of making a separate script for each select box's id. The reason is that I could be ending up with dozens of these select boxes on a page and all that repeated code just gets messy.
<select name="drop_list_menu_1" id="drop_list_menu_1">
<option value="letter:a">A</option>
<option value="letter:b">B</option>
<option value="letter:c">C</option>
</select>
<select name="drop_list_menu_2" id="drop_list_menu_2">
<option value="letter:a">A</option>
<option value="letter:b">B</option>
<option value="letter:c">C</option>
</select>
<select name="drop_list_menu_3" id="drop_list_menu_3">
<option value="letter:a">A</option>
<option value="letter:b">B</option>
<option value="letter:c">C</option>
</select>
My code to handle the onchange event:
<script type="text/javascript">
$(document).ready(function () {
// if user chooses an option from the select box...
$("#drop_list_menu_1").change(function () {
//doin some stuff
});
</script>
So, how can I get this:
$("#drop_list_menu_1").change(function () {
//doin some stuff
});
to catch any of the select boxes on the page being used? Something incorporating a regex?
Give the elements a common class (you can keep the id attributes if you want) and then use delegation:
$(document).on("change", "your-select-class", function() {
var changedElement = this;
// ...
});
You just need that one call to set up the event handler, and it'll work for as many copies as you need on the page.
You could use jQuery's attribute starts-with selector to select all drop-downs whose name begins with "drop_list_menu_":
$("select[name^='drop_list_menu_']").change(function(){
//doin some stuff
});
Assign same class to each Select and call it as below.
$(".ClassName").change(function (e) {
var SelectId = e.target.id
});
simple as that
$("select").change(function () {
alert('a');
});

Run function when a select option is selected twice in a row

I have a AJAX-loaded dropdown that runs a function when it's changed, but I also want it to run the function if the option that is already selected is clicked. (For example, someone selects option A two times in a row, I want it to run the function both times without having to select a different option between them)
JAVASCRIPT:
$(document).on('change','#dropdown',function(e){
//do stuff
}
HTML:
<select id="dropdown">
<option value="optionA">option A</option>
<option value="optionB">option B</option>
<option value="optionC">option C</option>
</select>
It took a bit of experimentation, but there is a way to detect if the dropdown menu of the select was clicked.
Move your code into the click event, and wrap an if tag around it as such:
if(event.pageY<0)
{
// The dropdown menu on the select was clicked!
}
The reason that only this if is needed, is because of the fact that both browsers I've managed to test this on, make it seem like the cursor is outside of the actual page when the event was triggered.
You can find the demo at http://jsfiddle.net/Entoarox/ATm43/.
The pageY property of the event object is one of the properties that jQuery normalizes for cross-browser consistency.
http://api.jquery.com/category/events/event-object/
Replace your on change script with:
$(document).on('click','#dropdown',function(event){
if(event.pageY >= 0) return; // return and don't do anything
// The dropdown menu on the select was clicked!
// do stuff
});
Use
$(document).on('select','#dropdown',function(e){
//do stuff
}
or
$(document).on('click','#dropdown',function(e){
//do stuff
}

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

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

Categories