Javascript - Append select lists from select - javascript

How can i auto generate multiple select lists from a select list like this example :
My code :
HTML:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="multiple.js"></script>
<div class="container">
<div id="selected_form_code">
<select id="select_btn">
<option value="0">--How many rooms ?--</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
</div>
<div id="form_submit">
<!-- Dynamic Registration Form Fields Creates Here -->
</div>
</div>
JS:
$(document).ready(function() {
$('select#select_btn').change(
function() {
var sel_value = $('option:selected').val();
$("#form_submit").empty(); //Resetting Form
// Below Function Creates Input Fields Dynamically
create(sel_value);
// Appending Submit Button To Form
}
);
function create(sel_value) {
for (var i = 1; i <= sel_value; i++) {
$("div#form1").append($("#form_submit"
).append($("<div/>", {id: 'head' }
).append($("<b>").text("Chambre " + i)),
$("<input/>",
{ type: 'text', placeholder: 'Chambre ' + i, name: 'Chambre-' + i } ) ))
}
}
});
This code only create text inputs. But, i need to display multiple rooms (chambre) by selecting the number from select option. After that, if il select N kids (enfants), N select should appears to choose their ages.
I hope it's clear :)

sorry, i'm not a big jquery fan, but as nobody answers, i try.
so fist, i would made some function get_chambre_html(cn) that will generate some Chambre html block, to append it in 'for' loop in your create().
then, next line after append() in create() function we may add change() event listeners for each new block, like you do it for chambres.
to add additional fields for each child we will append them to $('#ages'+chambre_index)[0]
<html><body>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div class="container">
<div id="selected_form_code">
<select id="select_btn">
<option value="0">--How many rooms ?--</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
</select>
</div>
<div id="form_submit">
<!-- Dynamic Registration Form Fields Creates Here -->
</div>
</div>
<script>
function get_chambre_html(cn)
{
return "<div>"
+ "<b>Chambre " + cn + ":</b> "
+ "Adultes: <select id='adultes" + cn + "'>"
+ "<option value='0'>--How many adults ?--</option>"
+ "<option value='1'>1</option>"
+ "<option value='2'>2</option></select>"
+ "<br/>Enfants: <select id='enfants" + cn + "'>"
+ "<option value='0'>--How many enfants ?--</option>"
+ "<option value='1'>1</option>"
+ "<option value='2'>2</option></select>"
+ "<div id='ages" + cn + "'></div>" // empty block for further usage
+"</div>";
}
$(document).ready(function()
{
$('select#select_btn').change(function()
{
var sel_value = $('option:selected').val();
$("#form_submit").empty(); //Resetting Form
// Below Function Creates Input Fields Dynamically
create(sel_value);
// Appending Submit Button To Form
});
function create(sel_value)
{
for (var i = 1; i <= sel_value; i++)
{
$("div#form1").append($("#form_submit").append(get_chambre_html(i)));
$("div#form1").append($("#form_submit").append("<div id='ages"+i+"'/>"));
$('select#enfants'+i).change(function(){
var infants = this.value;
var i=this.id.substr(7); // 7 = strlen of 'enfants'
for(var j=0; j<infants; j++)
$('#ages'+i).append(':[input age block '+i+']: ');
});
}
};
});
</script>

Related

How to retrieve data from array using $.getJSON?

I have a small web app where I need to populate a dropdown list after selecting another right before.
For example this is the URL of the Ajax request http://localhost:8080/ajax/dropdown_model?brandId=0 and the JSON code looks like this:
[{"id":0,"name":"Z-400","brand":{"id":0,"name":"Lenovo"}}]
The code I used is this one:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
var html = '';
$('select#brand').change(
function() {
$.getJSON("http://localhost:8080/ajax/dropdown_model", {
brandId : $(this).val(),
ajax : 'true'
}, function(data) {
html = '<option disabled="disabled" value="">Seleccionar modelo:</option>';
var len = data.length;
for ( var i = 0; i < len; i++) {
html += '<option value="' + data[i].id + '">'
data[i].id + ' : ' + data[i].name + '</option>';
}
html += '</option>';
$('select#model').html(html);
});
}); </script>
It should replace the content of the 2nd select tag adding into it the content of the JSON string.
Also this is the relevant part of the form (I'm using Spring and Thymeleaf):
<div class="brand" th:object="${lbra}">
<select name="brand" id="brand" >
<option value="">Seleccionar marca:</option>
<option th:each="brand : ${lbra}"
th:value="${brand.getId()}"
th:text="${brand.getId()}+' : '+${brand.getName()}"></option>
</select> </div>
<div class="model" id="modellist">
<select name="model" id="model">
<option value="" disabled="disabled" selected="selected">Seleccionar modelo:</option>
<option></option>
</select> </div>
I've removed some of the Spring variables for the sake of creating an example. You were missing a "+" after your dynamic option that is added to the HTML string (after html += '<option value="' + data[i].id + '">')..
var html = '';
$('select#brand').change(
function() {
$.getJSON("https://api.myjson.com/bins/ugf4v", {
brandId: $(this).val(),
ajax: 'true'
}, function(data) {
html = '<option disabled="disabled" value="">Seleccionar modelo:</option>';
var len = data.length;
for (var i = 0; i < len; i++) {
html += '<option value="' + data[i].id + '">' +
data[i].id + ' : ' + data[i].name + '</option>';
}
html += '</option>';
$('select#model').html(html);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="brand">
<select name="brand" id="brand">
<option value="">Seleccionar marca:</option>
<option>Test Change</option>
</select>
</div>
<div class="model" id="modellist">
<select name="model" id="model">
<option value="" disabled="disabled" selected="selected">Seleccionar modelo:</option>
<option></option>
</select>
</div>

Making text input invisible but tangible

I am working on a country dropdown filter for a search. This will allow users to search within the selected region.
Select 'Thailand' from the dropdown, 'Thailand + ' will be pushed to the search box which allows user to enter another keyword (e.g. Food) which forms into
'Thailand + Food'.
Due to technical constraints this is my only workaround creating a search filter. I am wondering can i make the selected region text invisible (Thailand +) yet when i press enter.. 'Thailand +' is part of the search results.
What i want to achieve:
User selects 'Thailand'
Thailand +' is pushed to textbox (Not visible to user)**
User types 'Food' in the search box
Both 'Thailand + Food' is in the search result
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="testfloat">
<select id="quantity">
<option selected>Select Libraries</option>
<option value="Albanian + ">Albanian</option>
<option value="Singapore + ">Singapore</option>
<option value="Malaysia + ">Malaysia</option>
<option value="Germany + ">Germany</option>
<option value="France + ">France</option>
<option value="Thailand + ">Thailand</option>
</select>
<script type="text/javascript">
$('#quantity').change(function(){
var qty = $('#quantity').val();
var total = qty;
$("#ms-helperText").val(total);
});
</script>
<input type="text" id="ms-helperText">
Instead of putting the selected country in the input, store it in a variable and change it accordingly.
This is how should be your code:
var searchedCountry = "";
$('#quantity').change(function() {
searchedCountry = $('#quantity').val();
$("#preview").html(searchedCountry + " " + $('#ms-helperText').val());
});
$('#ms-helperText').keyup(function() {
$("#preview").html(searchedCountry + " " + $(this).val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="testfloat">
<select id="quantity">
<option selected>Select Libraries</option>
<option value="Albanian + ">Albanian</option>
<option value="Singapore + ">Singapore</option>
<option value="Malaysia + ">Malaysia</option>
<option value="Germany + ">Germany</option>
<option value="France + ">France</option>
<option value="Thailand + ">Thailand</option>
</select>
<input type="text" id="ms-helperText">
<br/>
<div id="preview">
</div>
you could try to attach that value into a hidden input in html
<input type="hidden" id="somehiddenvalue"></input>
Concat both values into a hidden form element:
// Get all needed input elements
const $country = document.querySelector( '#country' );
const $quantity = document.querySelector( '#quantity' );
const $msHelperText = document.querySelector( '#ms-helperText' );
// Event handler
function inputChange() {
const collection = [];
$country.value && collection.push( $country.value );
$quantity.value && collection.push( $quantity.value );
// Only add + if both inputs have a value.
$msHelperText.value = collection.join( ' + ' );
console.log( 'Hidden element value: ', $msHelperText.value );
}
$country.addEventListener( 'input', inputChange );
$quantity.addEventListener( 'input', inputChange );
<select id="country">
<option value="" selected>Select Libraries</option>
<option value="Albanian">Albanian</option>
<option value="Singapore">Singapore</option>
<option value="Malaysia">Malaysia</option>
<option value="Germany">Germany</option>
<option value="France">France</option>
<option value="Thailand">Thailand</option>
</select>
<input type="text" id="quantity">
<!-- the new hidden form element, that will hold both values -->
<input type="hidden" id="ms-helperText">

how can i connect between two select tag

hi i have a select tag and i need if i click on any option from my first select.=====>i will get his attribute for it in the second select
my example is
<select name="select" >
<?php
$a={java,c++,php,python}
for($i=0;$i<4;$i++)
echo'<option value="'($i+1).'">'.$a[$i].' </option>';
}?>
</select>
<select name="select2" >
<?php
$after={{'j','jj','jjj'},
{'c','cc','ccc'},
{'p','pp','ppp'},
{'y','yy','yyy'}};
for($i=0;$i<3;$i++)
echo'<option value="'($i+1).'">'.$after[here the value of first select][$i].' </option>';
}?>
</select>
for example now if i chose java i need the select2 j jj jjj
if i chose c++ from the first select i need in the select 2 c cc ccc
i think it can be happen in jquerybut i don't know how it can be
Given your example, a possible output would be:
<select name="selectCode" >
<option></option>
<option value="1">java</option>
<option value="2">c++</option>
<option value="3">php</option>
<option value="4">python</option>
</select>
<br />
<select name="select2" style="display: none;">
</select>
The JQuery you want is:
var after = {};
after[1] = {0:"j",1:"jj",2:"jjj"};
after[2] = {0:'c',1:'cc',2:'ccc'};
after[3] = {0:'p',1:'pp',2:'ppp'};
after[4] = {0:'y',1:'yy',2:'yyy'};
$(function(){
$("select[name='selectCode']").on("change", function(){
console.log("selectCode Changed: " + $(this).val());
$("select[name='select2']").html("");
for(var i = 0; i<3; i++){
$("select[name='select2']").append("<option value='" + (i+1) + "'>" + after[$(this).val()][i] + "</option>").show();
}
});
});
jsFiddle example: http://jsfiddle.net/Twisty/xc4rs09m/

How to store in Array the parent IDs of elements with the same CLASS and display in alert these stored IDs

I am working on an existing website which limits me to touch HTML code. In the code below, there are 3 rows with the same CLASS (sameRow),.Row numbers may differ from case to case. Inside each row contains DIV with unique ID and a corresponding SELECT element with the same CLASS (sameSelect).
My target output is to be able create a JS/Jquery code to store these unique div IDs individually in the array and display each ID in the alert. Currently, my code below is displaying only the ID of the first DIV. The second and the third is not displayed. What could be wrong in my code?
Any help is greatly appreciated. Fiddle link here -> https://jsfiddle.net/philcyb/crkLgxhd/
HTML:
<div class="sameRow">
<div id="uniquediv1">
<select class="sameSelect">
<option>1</option>
<option selected>2</option>
</select>
</div>
</div>
<br />
<div class="sameRow">
<div id="uniquediv2">
<select class="sameSelect">
<option>1</option>
<option>2</option>
<option>3</option>
<option selected>4</option>
</select>
</div>
</div>
<br />
<div class="sameRow">
<div id="uniquediv3">
<select class="sameSelect">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6" selected>6</option>
</select>
</div>
</div>
JS/JQuery:
$(document).ready(function(){
var optionValue = new Array();
var rows = document.querySelectorAll('.sameRow').length;
alert("there are " + rows + " rows");
for(i = 0; i < rows; i++ ) {
optionValue[i] = $(".sameSelect").parent().attr("id");
alert("array row number " + i + " is " + optionValue[i]);
}
});
Just use eq
$(document).ready(function(){
var optionValue = new Array();
var rows = document.querySelectorAll('.sameRow').length;
alert("there are " + rows + " rows");
for(i = 0; i < rows; i++ ) {
optionValue[i] = $(".sameSelect").parent().eq(i).attr("id");
alert("array row number " + i + " is " + optionValue[i]);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div class="sameRow">
<div id="uniquediv1">
<select class="sameSelect">
<option>1</option>
<option selected>2</option>
</select>
</div>
</div>
<br />
<div class="sameRow">
<div id="uniquediv2">
<select class="sameSelect">
<option>1</option>
<option>2</option>
<option>3</option>
<option selected>4</option>
</select>
</div>
</div>
<br />
<div class="sameRow">
<div id="uniquediv3">
<select class="sameSelect">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6" selected>6</option>
</select>
</div>
</div>
$(document).ready(function(){
var optionValue = new Array();
$('.sameRow').each(function(i){
optionValue[i] = $(this).find('.sameSelect').parent().attr("id");
alert("array row number " + (i + 1) + " is " + optionValue[i]);
});
});
JSFIDDLE
I think in this case no need for array you can use
$(document).ready(function(){
$('.sameRow').each(function(i){
var getID = $(this).find('.sameSelect').parent().attr("id");
alert("array row number " + (i + 1) + " is " + getID);
});
});
JSFIDDLE

jQuery append list of x elements

I am trying to understand how can I make a list of x elements when a value change.
Let's go with the example
HTML
<select class="num">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select>
<div class="list"></div>
jQuery
<script>
$('.num').change(function() {
num_val = $(this).val(); // get the number of the elements that will be shown
for (i =0; i == num_val; i++) { // I do a for loop for append each div to the list but it doesn't work it's show me just 1.
$('.list').append('<div>' + i + '</div>');
}
});
</script>
So, how can I display X number element equal to the value on select input?
Change you html into:
<select class="num">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select>
or the value will be always 1, and you'll add only one element.
Than cange you loop condition into:
$('.num').change(function () {
num_val = $(this).val(); // get the number of te elements that will be shown
$('.list').empty();
for (i = 0; i < num_val; i++) { // i do a for loop for append each div to the list but it doesn't work it's show me just 1.
$('.list').append('<div>' + i + '</div>');
}
});
I used $('.list').empty(); to clear the list before append elements to it.
Demo: http://jsfiddle.net/IrvinDominin/Y79ec/
DEMO
note the changed value
<option value="3">3</option>
$('.num').change(function() {
for (var i=0; i<this.value; i++) {
$('.list').append('<div>' + (i+1) + '</div>');
}
});
Performance-wise it's a bad idea to catch your .list element and create HTML elements
all over again in a loop, so a better approach would be:
var list = '';
$('.num').change(function() {
for (var i=0; i<this.value; i++) {
list += '<div>' + (i+1) + '</div>';
}
$('.list').append( list ); // only once after the loop.
});
try something like this
html code
<select class="num">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select>
javascript code
$(document).ready(function(){
$('.num').change(function() {
$('.list').html('');
var num_val = parseInt($(this).val()); // get the number of te elements that will be shown
console.log(num_val);
for (var i =1; i <= num_val; i++) {
$('.list').append('<div>' + i + '</div>');
}
});
});

Categories