Fill select list with values depending on preselection - javascript

I want to have one select list populated with different values (price) depending on which option was chosen in other select list (sale or rent)
So what I have done is first create the arrays for sale and rent.
Then get the jquery and do an change event to pick which selection was made.
then a Switch statement that should populate the select list in question, but it is not showing anything. While jquery is a library for javascript I dont know if mixing them like I have done is alright:
$('#transaction').change(function(){
$value = $('#transaction').val();
var sale = [];
for (var i = 350000; i <= 2000000; i+100000) {
sale.push(i);
}
var rent = [];
for (var i = 500; i <= 6000; i+100) {
rent.push(i);
}
switch($value) {
case 'sale':
$.each(sale, function(key, value){
$('#price').append('<option value="' + index+ '">' + value + '</option>')
break;
case 'rent':
break;
}); // end of each
} // end of switch
}) ; //end of jquery snippet
<div class="row">
<div class="col-md-2 col-md-offset-1">
<div class="form-group">
{{Form::label('transaction', 'Transaction')}}
<select name="transaction" id="transaction" class="form-control">
<option value="select">Select</option>
<option value="sale">Sale</option>
<option value="rent">Rent</option>
<option value="holiday">Holiday</option>
</select>
</div>
</div>
<div class="col-md-2">
<div class="form-group">
{{Form::label('price', 'Price')}}
<select name="price" id="price" class="form-control">
</select>
</div>
</div>

You dont have the options element in your select tag, so it never gets the $value from this statement :- $value = ('#transaction').val();
Insert the option tags and then run your example.

All credits go to Keith Wood (Sydney)
$(function() {
$('#transaction').change(function() {
var sale = [];
for (var i = 350000; i <= 2000000; i += 100000) {
sale.push(i);
}
var rent = [];
for (var i = 500; i <= 6000; i += 100) {
rent.push(i);
}
var option = $('#transaction').val();
var prices = (option === '1' ? sale : (option === '2' ? rent : []));
var options = '';
$.each(prices, function(key, value) {
options += '<option value="' + value + '">' + value + '</option>';
});
$('#price').html(options);
});
});
<div class="col-md-2 col-md-offset-1">
<div class="form-group">
{{Form::label('street', 'Transaction')}}
<select name="transaction" id="transaction" class="form-control">
<option value="0">Select</option>
<option value="1">Sale</option>
<option value="2">Rent</option>
<option value="3">Holiday</option>
</select>
</div>
</div>
<div class="col-md-2">
<div class="form-group">
{{Form::label('price', 'Price')}}
<select name="price" id="price" class="form-control">
</select>
</div>
</div>

Related

append() in jquery not woring

I am new to jquery and ajax. I really need you help.
I have two select box, one dynamically add options to a select when the first select box is checked. I used ajax to dynamically get those values. I am getting values correctly from database. But when I try to append these options inside second select box it is not working. My code is below
$(document).ready(function() {
$("#categories").change(function() {
var categoryId = $("#categories").val();
//alert(categoryId);
if(categoryId == 2) {
$.ajax({
url: "<?= base_url();?>Web/getRateType",
method: "POST",
dataType: "json",
success:function(data) {
//alert(data[0].status);
$("#rate_container").css('display', 'block');
$("#expected_salary_container").css('display', 'none');
$("#rate_categories").empty();
// var str = '<label>Rate*</label></br>';
//str += '<select name="rate_categories" style="font-size:15px" id="rate_categories"><option value="0">Select</option>';
var str = '';
$.each(data, function(key, value) {
//alert(value['rate_id']);
str +='<option value="'+ value['rate_id'] +'">'+ value['rate_cat_name'] +'</option>';
});
alert(str);
//str += '</select>';
var x = $("#rate_categories").append(str);
if(x){
alert(x);
}
}
});//$("#rate_categories").append('<option value="'+ value.rate_id +'">'+ value.rate_cat_name +'</option>');
}
else if (categoryId == 1) {
document.getElementById("expected_salary_container").style.display = "block";
document.getElementById("rate_container").style.display = "none";
}
else{
document.getElementById("expected_salary_container").style.display = "none";
document.getElementById("rate_container").style.display = "none";
}
});
<div class="col-lg-6 col-md-6">
<div class="form-group">
<label>Job Type*</label>
<select name="categories" id="categories">
<option value="0">Select</option>
<?php foreach($categories as $key => $value) { ?>
<option value="<?php echo $value['type_id']; ?>"><?php echo $value['cat_name']; ?></option>
<?php } ?>
</select>
</div>
</div>
<div class="form-group">
<label>Rate*</label>
<select id="rate_categories" name="rate_categories">
<option value="0">Select</option>
</select>
</div>
here alert(x) is working fine. but the html is not appending inside select box. could anybody please help
jQuery is referenced in the header:
<script src="https://code.jquery.com/jquery-3.6.0.js" integrity="sha256-H+K7U5CnXl1h5ywQfKtSj8PCmoN9aaq30gDh27Xc0jk=" crossorigin="anonymous"></script>
You are calling the ready function before the jQuery JavaScript is included. Reference jQuery first. However please check the network tab JS file load.
You should put the references to the jquery scripts first.
<script language="JavaScript" type="text/javascript" src="/js/jquery-1.2.6.min.js"></script>
Please use compatible new jquery CDN Url in above script tag.
Examine the code below and see if that works for you. I've changed the vanilla JS to jQuery. You may need to re-insert your php code back in.
$(document).ready(function() {
//Hide everything
$("#expected_salary_container, #rate_container").hide();
$("#categories").change(function() {
var categoryId = $("#categories").val();
console.log(categoryId);
//alert(categoryId);
if (categoryId == 2) {
let data = ["Item 1", "Item 2", "Item 3"];
str = "";
$.each(data, function(key, value) {
//alert(value['rate_id']);
str += '<option value="' + value + '">' + value + '</option>';
console.log(str);
});
var x = $("#rate_categories").append(str);
$("#expected_salary_container").hide();
$("#rate_container").show();
} else if (categoryId == 1) {
$("#expected_salary_container").show();
$("#rate_container").hide();
} else {
$("#expected_salary_container").hide();
$("#rate_container").show();
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="col-lg-6 col-md-6">
<div class="form-group">
<label>Job Type*</label>
<select name="categories" id="categories">
<option value="0">Select</option>
<option value="2">Cat 1</option>
<option value="1">Cat 2</option>
<option value="2">Cat 3</option>
</select>
</div>
</div>
<div id="rate_container">
<div class="form-group">
<label>Rate*</label>
<select id="rate_categories" name="rate_categories">
<option value="0">Select</option>
</select>
</div>
</div>
<div id="expected_salary_container">
<div class="form-group">
<label>Salary*</label>
<select id="rate_categories" name="rate_categories">
<option value="0">Select</option>
</select>
</div>
</div>

generate dynamic div and retrieve value of input elements

I am having div with input elements with Add and Cancel buttons.
When user clicked on add Button,I need to generate div with the same input elements and capture the value to JSon object.
Here is my code snippet
<div id="filterfields" class="row collapse">
<form class="form-inline" id="filterFieldsForm">
<select class="form-control" name="TypeCode" id="filterType_0">
<option value="Type">Type</option>
<option value="SubmittedBy">SubmittedBy</option>
<option value="Date">Date</option>
<option value="Description">Description</option>
</select>
<select class="form-control" name="Filter" id="filterCondition_0">
<option value="Equal">Equal</option>
<option value="StartsWith">Starts With</option>
<option value="EndsWith">Ends With</option>
<option value="Greaterthan">Greater Than</option>
<option value="Lessthan">Less Than</option>
</select>
<input type="text" name="caseFilterText" class="form-control" id="filterText_0">
<input class="form-control" type="radio" name="inlineRadioOptions" id="andRadio_0" value="AND">
<label for="andRadio">AND</label>
<input class="form-control" type="radio" name="inlineRadioOptions" id="orRadio_0" value="OR">
<label for="orRadio">OR</label>
<button id="addBtn_0" type="button" class="btn btn-secondary">Add</button>
<button id="cancelBtn_0" type="button" class="btn btn-secondary">Cancel</button>
</form>
</div>
I tried with clone and trying to retrieve values from the input elements inside div,but I am facing issue with getting values and generating ids.
$('#addBtn_' + count).click(function () {
var newel = $("#filterfields").clone(true);
var jsonData = [];
$(newel).insertAfter("#filterfields");
var index;
$("#filterfields").find('input:text,select').each(function () {
let str = '{"' + this.id + '":' + (this.value + '}';
jsonData.push(str);
}).end()
newel.find(':input').each(function () {
var oldId = $(this).attr("id");
var split = oldId.toString().split('_');
index = parseInt(split[1]);
var curId = split[0];
var newId = curId + "_" + index + 1;
this.id = newId;
}).end()
jsonData.push('"filterClause":' + $('input[name="inlineRadioOptions"]:checked').val() + '"');
});
Please suggest me if there is better way to achieve the similar function as I am not able to get values of input elements of current row.
Consider the following code.
$(function() {
function formToJson(fObj) {
var j = [];
fObj.children().not("button, label").each(function(i, el) {
// Will avoid buttons and labels
if (!($(el).is(":radio") && !$(el).is(":checked"))) {
// Will avoid unselected Radio Buttons
var d = {
nodeName: $(el).prop("nodeName"),
props: {
class: $(el).attr("class"),
id: $(el).attr("id")
},
value: $(el).val(),
name: $(el).attr("name")
};
if (d.nodeName != "SELECT") {
d.props.type = $(el).attr("type");
}
j.push(d);
}
});
return j;
}
$("[id^='addBtn']").click(function() {
var jsonData = formToJson($("#filterFieldsForm"));
console.log(jsonData);
var filter = "Filter: ";
$.each(jsonData, function(key, item) {
if (key != 2) {
filter += item.value + " ";
} else {
filter += "'" + item.value + "' ";
}
});
$("<div>", {
class: "filter-results"
}).html(filter).appendTo("body");
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="filterfields" class="row collapse">
<form class="form-inline" id="filterFieldsForm">
<select class="form-control" name="TypeCode" id="filterType_0">
<option value="Type">Type</option>
<option value="SubmittedBy">SubmittedBy</option>
<option value="Date">Date</option>
<option value="Description">Description</option>
</select>
<select class="form-control" name="Filter" id="filterCondition_0">
<option value="Equal">Equal</option>
<option value="StartsWith">Starts With</option>
<option value="EndsWith">Ends With</option>
<option value="Greaterthan">Greater Than</option>
<option value="Lessthan">Less Than</option>
</select>
<input type="text" name="caseFilterText" class="form-control" id="filterText_0">
<input class="form-control" type="radio" name="inlineRadioOptions" id="andRadio_0" value="AND">
<label for="andRadio">AND</label>
<input class="form-control" type="radio" name="inlineRadioOptions" id="orRadio_0" value="OR">
<label for="orRadio">OR</label>
<button id="addBtn_0" type="button" class="btn btn-secondary">Add</button>
<button id="cancelBtn_0" type="button" class="btn btn-secondary">Cancel</button>
</form>
</div>
As you are iterating over elements, it is best to use .each(). Using the proper selector, we can target just the form elements you want. You then want a condition to ensure that if a Radio Button is selected (or checked) that it is included and others are excluded.
The result is an Array of Objects that can be used to rebuild the HTML Structure or just build new copies.
Update
$(function() {
function formToJson(fObj) {
var j = [];
fObj.each(function(i, el) {
var d = {};
$("select, input", el).each(function(k, v) {
if (!($(v).is(":radio") && !$(v).is(":checked"))) {
d[$(v).attr("id")] = $(v).val();
}
});
j.push(d);
});
return j;
}
$("[id^='addBtn']").click(function() {
var jsonData = formToJson($("#filterFieldsForm"));
console.log(jsonData);
var filter = "Filter: ";
$.each(jsonData, function(key, item) {
if (key != 2) {
filter += item.value + " ";
} else {
filter += "'" + item.value + "' ";
}
});
$("<div>", {
class: "filter-results"
}).html(filter).appendTo("body");
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="filterfields" class="row collapse">
<form class="form-inline" id="filterFieldsForm">
<select class="form-control" name="TypeCode" id="filterType_0">
<option value="Type">Type</option>
<option value="SubmittedBy">SubmittedBy</option>
<option value="Date">Date</option>
<option value="Description">Description</option>
</select>
<select class="form-control" name="Filter" id="filterCondition_0">
<option value="Equal">Equal</option>
<option value="StartsWith">Starts With</option>
<option value="EndsWith">Ends With</option>
<option value="Greaterthan">Greater Than</option>
<option value="Lessthan">Less Than</option>
</select>
<input type="text" name="caseFilterText" class="form-control" id="filterText_0">
<input class="form-control" type="radio" name="inlineRadioOptions" id="andRadio_0" value="AND">
<label for="andRadio">AND</label>
<input class="form-control" type="radio" name="inlineRadioOptions" id="orRadio_0" value="OR">
<label for="orRadio">OR</label>
<button id="addBtn_0" type="button" class="btn btn-secondary">Add</button>
<button id="cancelBtn_0" type="button" class="btn btn-secondary">Cancel</button>
</form>
</div>
This will target the various rows and for each row, it will gather all the Select and Inputs.

Get ID of all child elements and its input/select data

How can I get the id of each child element and its tag name so I can save the data of each column to a string?
<div class="row">
<div class="col-md-4">
<input id="poz-3" placeholder="numv" type="text">
</div>
<div class="col-md-4">
<input id="poz-3" placeholder="numv" type="text">
</div>
<div class="col-md-4">
<select id="poz-3-s">
<option value="1">-Pick-</option>
<option value="2">test2</option>
<option value="3">test3</option>
</select>
</div>
</div>
I've got the loop so far, but I don't know how to get the data depending on the input/select:
for (var j = 0; j < (nCols / nRows); j++) {
}
You could use .find('*') to get all the childs :
$('.row').find('*').each(function(){
//Get the id and value
})
Hope this helps.
$('.row').find('*').each(function(){
if($(this).prop('tagName')!='OPTION')
console.log("id = "+$(this).prop('id')+" / value = "+$(this).val());
else
console.log("id = "+$(this).prop('id')+" / value = "+$(this).text());
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="row">
<div class="col-md-4">
<input id="poz-3" placeholder="numv" type="text" value='first input'>
</div>
<div class="col-md-4">
<input id="poz-3" placeholder="numv" type="text" value='second input'>
</div>
<div class="col-md-4">
<select id="poz-3-s">
<option value="1">-Pick-</option>
<option value="2" selected>test2</option>
<option value="3">test3</option>
</select>
</div>
</div>
If I understood you correctly you can get all input's values simply by iterating through them with jQuery:
$.each($('.col input, .col select'), function(index, item) {
console.log('ELEMENT ID ' + $(item).attr('id') + ' VAL - ' + $(item).val());
});
of simply use serializeArray method like this:
$('input, select').serializeArray()
Working example of both ways here: https://jsfiddle.net/hc882g27/
P.S.: in pure javascript it could be done with querySelectorAll function:
var items = document.querySelectorAll('.col input, .col select');
for (var i = 0; i < items.length; i++) {
console.log(items[i].value);
}

jquery append not working properly in my application

i have a javascript which is generating the below html dynamically. I want those two dropdowns for all list elemnts. Here it is happening only for last list element.
<ul id="drivernvehicle">
<li>
<div class="form-group" id="1"></div>1.</li>
<li>
<div class="form-group" id="2"></div>2.</li>
<li>
<div class="form-group" id="3"></div>3.</li>
<li>
<div class="form-group" id="4"></div>4.
<select class="form-control input-lg required">
<option value="M" selected="selected"><--select Driver--></option>
<option value="25">25</option>
</select>
<select class="form-control input-lg required">
<option value="N" selected="selected"><--select Vehicle--></option>
<option value="23">23</option>
</select>
</li>
</ul>
JS
$('#drivernvehicle').empty();
var i = $('#noOfVehicle').val();
var j;
var temp;
var items = [];
for (j = 0; j < i; j++) {
temp = j + 1;
//var selectDiv = selectDiv + temp;
var selectDiv = $("<li><div class=\"form-group\" id=\"" + temp + "\"></div></li>");
selectDiv.append(temp + ". ")
.append(driverSelectBox)
.append(vehicleSelectBox);
items.push(selectDiv);
}
$('ul#drivernvehicle').append(items);
javascript below which generate above html. here "driverSelectBox" and "vehicleSelectBox" are two dropdown which has been crated dynamically.
You need to have something to display.
Here's a jsFiddle: http://jsfiddle.net/t8jo77Le/
I hardcoded/deleted the stuff you failed to include.
I added the 'Hello' here:
$("<li><div class=\"form-group\" id=\"" + temp + "\">Hello</div></li>");
Without it, it doesn't display.

Javascript hide values depending on a selected option

I need help with some javascript. The idea is to hide some values from a depending on a parent
here is the html
<div class="form-group" style="margin-top: 20px;">
<label for="inputPassword3" class="col-sm-2 control-label">Phase</label>
<div class="col-sm-10">
<select class="form-control" name="phase" id="phase">
{%if phases is defined%}
{%for phase in phases%}
<option value="{{phase.id}}">{{phase.nom}}</option>
{%endfor%}
{%endif%}
</select>
</div>
</div>
<div class="form-group" >
<label for="inputPassword3" class="col-sm-2 control-label">Sous phase</label>
<div class="col-sm-10">
<select class="form-control" name="ssphase" id="ssphase">
{%if ssphases is defined%}
{%for ssphase in ssphases%}
<option value="{{ssphase.id}}" id="{{ssphase.phaseid}}">{{ssphase.nom}}</option>
{%endfor%}
{%endif%}
</select>
</div>
</div>
Do you have any idea to make the javascript hide options with the id that doesnt match with the value of the option selected on the first select?
Thanks for helping !
You can do it like this:
phase.onchange = function () {
show_sphases (this.value);
}
function show_sphases (phase) {
var subphases = document.querySelectorAll("[data-phase='" + phase + "']");
var allSubphases = document.querySelectorAll("#ssphase option");
for (var i = 0; i <= allSubphases.length; i++ ){
var item = allSubphases.item(i);
$(item).hide();
}
for (var i = 0; i <= subphases.length; i++ ){
var item = subphases.item(i);
$(item).show();
}
}
You also have to add a data-phase attribute to your ssphases options so that you can link them together, like this:
<option value="11" id="11" data-phase="1">Subphase #1-1</option>
I used jQuery for $().hide and $().show.
Here's a fiddle.

Categories

Resources