var regionOption = document.querySelector("#municipality");
var districtOption = document.querySelector("#districtName");
var provOption = document.querySelector("#region");
createOption(provOption, Object.keys(regions));
provOption.addEventListener('change', function() {
createOption(regionOption, regions[provOption.value]);
});
regionOption.addEventListener('change', function() {
createOption(districtOption, districts[regionOption.value]);
});
function createOption(dropDown, options) {
dropDown.innerHTML = '';
options.forEach(function(value) {
dropDown.innerHTML += '<option name="' + value + '">' + value + '</option>';
});
};
CSS:
<select id="region" style="width: 125px;"></select>
<select id="municipality" style="width: 125px;"></select>
<select id="districtName" style="width: 125px;"></select>
So, I'm populating options for an empty select and I was wondering how to get the value of the selected option. I basically want to check if (select value = 'A' && another selecte value = 'B') { do something}
Set the value attribute on each <option>:
<option value="' + value + '">
Then, simply check the value property on the <select>.
if (document.getElementById("region").value === 'A') {
// ...
}
Related
Taka a look at this fiddle here this is a form where a business user enters the offered services.I sent the data with ajax and by serializing the form.
Click edit and add(plus sign) a service...in the example an input is added where it's name attribute value is of this **form= form[5]...**contrast with this with the form of the name attribute value in the other inputs...only the newly added services have the name attribute like this and the reason for that is to serialize only these...and not the others already present in the DOM/stored in the DB.
And now my problem:
Imagine that the user goes to edit the already registered services(or that he goes to edit them and add a new one)...at this case the already registered services wont'be serialized cause of the form the name attribute value has...(and the reason for this is explained above).
What can I do in this case?Sometimes I must serialize only part of a form and sometimes whole of the form.If all the inputs have name attribute value of form[1....] then along with the newly added input...already registered services will be serialized again.
Thanks for listening.
Code follows(you can see it in the fiddle too)
$('.editservices').click(function() {
//console.log(('.wrapper_servp').length);
originals_ser_input_lgth = $('.services').length;
var originals = [];
$('.show_price')
// fetch only those sections that have a sub-element with the .value
class
.filter((i, e) => $('.value', e).length === 1)
// replace content in remaining elements
.replaceWith(function(i) {
var value = $('.value', this).data('value');
var fieldsetCount = $('#serv').length;
var index = fieldsetCount + i;
return '<div class="show_price"><p id="show_p_msg">Price
visibility</p></div>' + '\
<div class="show_p_inpts">' +
'<input class="price_show"' + (value == 1 ? "checked" : "") + '
type="radio" name="form[' + index + '][price_show]" value="1">yes' +
'<input class="price_show"' + (value == 0 ? "checked" : "") + '
type="radio" name="form[' + index + '][price_show]" value="0">no' +
'</div>'; // HTML to replace the original content with
});
$('#buttons').removeClass('prfbuttons');
$('#saveserv').addClass('hideb');
$('.actionsserv').removeClass('actionsserv');
priceavail = $(".price_show:input").serializeArray();
});
$('#addser').on('click', function() {
$('#saveserv').css('border','2px solid none');
var serviceCount = $('input.services').length + 1;
var serv_inputs = '<div class="wrapper_servp"><div class="serv_contain">\n\
<input placeholder="service" class="services text" name="form[' + serviceCount + '][service]" type="text" size="40"> \n\
<input placeholder="price" class="price text" name="form[' + serviceCount + '][price]" type="text" size="3"></div>';
var p_show = '<div class="show_p">' +
'<p id="show_p_msg">Price visibility;</p>' +
'<span id="err_show_p"></span><br>' +
'</div>';
var inputs = '<div class="show_p_inpts">' +
'<input class="price_show" type="radio" name="form[' + serviceCount + '][price_show]" value="1">yes' +
'<input class="price_show" type="radio" name="form[' + serviceCount + '][price_show]" value="0">no' +
'</div></div>';
$('.wrapper_servp').last().after(serv_inputs + p_show + inputs);
$('#saveserv').removeClass('hideb');
$('#remser').css('display', 'inline');
});
$('#cancelserv').click(function(e) {
e.preventDefault();
//var newinputs = $('.wrapper_servp').length;
//var inp_remv = newinputs - originals_ser_input_lgth;
//$('.wrapper_servp').slice(-inp_remv).remove()
$('.show_p_inpts')
.filter((i, e) => $('.price_show:checked', e).length === 1)
.replaceWith(function(i) {
var value = $('.price_show:checked').attr('value');
return '<span data-value="' + value + '" class="value">' + (value == 1 ? "yes" : "no") + '</span>'
});
});
var groupHasCheckedBox = function() {
return $(this).find('input').filter(function() {
return $(this).prop('checked');
}).length === 0;
},
inputHasValue = function(index) {
return $(this).val() === '';
};
$('#saveserv').click(function(e) {
e.preventDefault();
//from here
var $radioGroups = $('.show_p_inpts');
$('.show_p_inpts').filter(groupHasCheckedBox).closest('div').addClass("error");
$('.services, .price').filter(inputHasValue).addClass("error");
//to here
var $errorInputs = $('input.services').filter((i, e) => !e.value.trim());
if ($errorInputs.length >= 1) {
console.log($errorInputs);
$('#err_message').html('you have to fill in the service'); return;
}
if ($('input.price').filter((i, e) => !e.value.trim()).length >= 1) {
$('#err_message').html('you have to fill in the price'); return;
}
});
var IDs=new Array();
$('body').on('click', '#remser', function(e){
var inputval=$('.services:visible:last').val();
if(inputval!=='')
{r= confirm('Are you sure you want to delete this service?');}
else
{
$('.wrapper_servp:visible:last').remove();
}
switch(r)
{
case true:
IDs.push($('.services:visible:last').data('service'));
$('.wrapper_servp:visible:last').addClass('btypehide');
if($('.serv_contain').length==1)$('#remser').css('display','none');
$('#saveserv').removeClass('hideb').css('border','5px solid red');
//originals.servrem=true;
break;
case false:var i;
for(i=0;i<originals.ser_input_lgth;i++)
{
$('input[name="service'+i+'"]').val(services[i].value);
$('input[name="price'+i+'"]').val(prices[i].value);//εδω set value
}
$('.services').slice(originals.ser_input_lgth).remove();
$('.price').slice(originals.ser_input_lgth).remove();
$('.openservices').addClass('hide').find('.services,.price').prop('readonly', true);
var text='<p class="show_price">Θες να φαίνεται η τιμή;<span data-value="'+ show_pr_val.value +'" class="value">' +(show_pr_val.value==1 ? 'yes':'no') + '</span></p>';
$('.show_p_inpts').remove();
$('.show_price').replaceWith(text);;
break;
}
});
I have an Idea for you. What you can do is when you show the currently existed value in you html instead of giving name attribute just give data-name attribute. I.e
Change this
<input class="services text" data-service="21" size="40" value="hair" type="text" name="service0" readonly="">
To This
<input class="services text" data-service="21" size="40" value="hair" type="text" data-value="hair" data-name="service0" readonly="">
Now when user update this values you can bind an event in jQuery like below.
$(document).ready(function(){
$(".services input").on("change paste keyup", function() {
if($(this).val() === $(this).attr("data-value"))
{
$(this).removeAttr("name");
}else{
$(this).attr("name",$(this).attr("data-name"));
}
});
});
By this way you can give name attribute to only those elements whose values are changed. Now each time you can serialize the whole form and it will only get the value of changed elements.
Don't forget to give unique class to already existed elements so you can bind on change event. Hope its clear to you.
So, i have a simple form like this:
<div class="form-group">
<label class="">No Inventaris</label>
<div id="container">
<input type="button" name="noInv" class="form-control" id="add_field" value="Klik untuk membuat text field baru"><br>
<script type="text/javascript">
var count = 0;
$(function(){
$('#add_field').click(function(){
count += 1;
$('#container').append(
'<strong >No Inv Barang Ke ' + count + '</strong><br />'
+ '<select id="field_' + count + '" name="fields[]' + '" class="form-control no_inv"><?php $noInv = $this->modelku->select_inv() ?> <?php foreach($noInv->result() as $inv){ ?> <option value="<?php echo $inv->no_inv ?>"><?php echo $inv->no_inv ?></option><?php } ?></select><br>' );
});
});
</script>
</div>
When i click the button the field will regenerate select option, and the value is from database
select_inv function:
public function select_inv()
{
$this->db->select("no_inv");
$this->db->from('detail_barang');
$this->db->where("kondisi = 'Ada' ");
$query = $this->db->get();
return $query;
}
My Question: How can i disable value in select option when it already selected by another select option?
Try this if this is what you need.
i just created a sample dropdown and in my jquery i trigger the event change using the class of all select option then i will get the value of the select and id. after getting the value i check the val if it is empty or not if not empty then i will use the each function for all the select and get their id attribute so i can compare it with the id of the select and if their id is not the same then i will disabled the option with the same value of the selected dropdown.
and i use focus event for getting the previous value so i can reset whether the user change the value of the selected option.
$( document ).ready(function() {
$('body').on('click','#add_field',function(){
count += 1;
$('#container').append(
'<strong >No Inv Barang Ke ' + count + '</strong><br />'
+ '<select id="field_' + count + '" name="fields[]' + '" class="form-control no_inv select_alternate"> <option value="">select</option><option value="test1">test1</option><option value="test2">test2</option><option value="test3">test3</option></select><br></select><br>' );
});
var count =0;
var previous;
var selectedData = [];
$('body').on('click','.select_alternate',function(){
previous = this.value;
});
$('body').on('change','.select_alternate',function(){
var val = this.value;
var id = $(this).attr('id');
if(val != ''){
$(".select_alternate").each(function(){
var newID = $(this).attr('id');
if(id != newID){
$('#'+newID).children('option[value="' + val + '"]').prop('disabled',true);
$('#'+newID).children('option[value="' + previous + '"]').prop('disabled',false);
selectedData.splice($.inArray(val, selectedData),1);
}else{
selectedData.push(val);
}
});
}else{
$(".select_alternate").each(function(){
var newID = $(this).attr('id');
if(id != newID){
$('#'+newID).children('option[value="' + previous + '"]').prop('disabled',false);
}
});
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group">
<label class="">No Inventaris</label>
<div id="container">
<input type="button" name="noInv" class="form-control" id="add_field" value="Klik untuk membuat text field baru"><br>
</div>
Suppose I have this HTML
<form action="#" action="get">
<select name="college" id="college" onchange="selection('college', 'course')">
<option value="">Select an Option</option>
<option value="amity">Amity University</option>
<option value="indraprastha">Indraprasth University</option>
</select>
<br>
<select name="course" id="course" onchange="selection('course', 'stream')" >
<option value="">Select an Option</option>
</select>
<br>
<select name="stream" id="stream">
<option value="">Select an Option</option>
</select>
</form>
I have this JSON,
{
"amity":{
"course":[
{
"name":"B.Tech",
"value":"btech",
"stream":[
{
"name":"Computer Science",
"value":"cse"
},
{
"name":"Information Technology",
"value":"cse"
},
{
"name":"Aerospace Engg.",
"value":"cse"
}
]
},
{
"name":"M.Tech",
"value":"mtech",
"stream":[
{
"name":"Networking",
"value":"net"
},
{
"name":"telecommunications",
"value":"tc"
}
]
}
]
}
}
The Javascript is,
function selection(s1, s2) {
var first = document.getElementById(s1),
second = document.getElementById(s2);
var college = $('#college').val(),
cr = $('#course').val(),
st = $('#stream').val(),
se = $('#sem').val();
$.getJSON("json/select.json", function(data) {
switch(s1) {
case 'college':
$.each(data[college].course, function(key, value) {
second.innerHTML += '<option value="'+ value.value +'">'+ value.name +'</option>';
}); break;
case 'course':
$.each(data[college].course[].stream, function(key, value) {
second.innerHTML += '<option value="'+ value.value +'">'+ value.name +'</option>';
}); break;
}
});
}
I am making a dynamic drop-down menu where the next drop down values are fetched from JSON object file, using the reference of previous values. As suggested from my this question (link), I am able to get the value of course (second drop-down) using the course array in the object.
Now, since the values in the second select menu(course) are filled dynamically, I can't figure out how to take the corresponding course array element to fill the next select menu options for stream array.
Since the course property in JSON is an array, I don't know which index element element is chosen from second menu (See the switch case for 'course', the data[college].course[] index is empty). The hardcoded [0] works, but that's not dynamic then.
How to access the stream array using the values of course grabbed from second menu.
I hope I am clear. Thanks in advance!
Just iterate through array of courses to get the stream dynamically:
for (var i = 0; i < data[college].course.length; i++) {
currentStream = data[college].course[i].stream;
}
I.e. using your code:
for (var i = 0; i < data[college].course.length; i++) {
$.each(data[college].course[i].stream, function(key, value) {
second.innerHTML += '<option value="'+ value.value +'">'+ value.name +'</option>';
});
}
Finding the current stream for your selected course:
// assuming cr = "btech"
for (var i = 0; i < data[college].course.length; i++) {
if (data[college].course[i].value == cr) {
currentStream = data[college].course[i].stream;
break;
}
}
$.each(currentStream, function(key, value) {
second.innerHTML += '<option value="'+ value.value +'">'+ value.name +'</option>';
});
function selection(s1, s2) {
var first = document.getElementById(s1),
second = document.getElementById(s2);
var college = $('#college').val(),
cr = $('#course').val(),
st = $('#stream').val(),
se = $('#sem').val();
$.getJSON("json/select.json", function(data) {
switch(s1) {
case 'college':
$.each(data[college].course, function(key, value) {
second.innerHTML += '<option value="'+ value.value +'">'+ value.name +'</option>';
}); break;
case 'course':
var course = data[college].course;
for(var i = 0;i<course.length;i++){
if(course[i].name === cr){ //cr is selected option
$.each(course[i].stream, function(key, value) {
second.innerHTML += '<option value="'+ value.value +'">'+ value.name +'</option>';
}
}
}); break;
}
});
}
$.each(data.aaData, function(i, obj) {
var opt_data = "<option value=" + obj.value + ">" + obj.text + "</option>";
$(opt_data).appendTo('#reqtype');
});
alert($('#reqtype :selected').text());
var numberOfOptions = $('select#reqtype option').length
alert(numberOfOptions);
After appending the option values to 'reqtype' selectcombobox through jquery, i tried to alert the number of option values and selectedvalue. Its showing the correct number. But in select combobox is not listing the values.still its empty.
I tried with different jqueries, its values are showing properly through jquery. But its not displaying the select options in HTML view.select combobox is empty only.
Here is what you should try:
var opt_data = '';
$.each(data.aaData, function(i, obj) {
opt_data += "<option value=" + obj.value + ">" + obj.text + "</option>";
});
$('#reqtype').html(opt_data);
alert($('#reqtype :selected').text());
Iam using MVC4, initially my dropdown displays the list of data,
My javascript looks like,
$.each(data, function (value, key) {
var opt = "<option value=\"" + key + "\">" + value + "</option>";
$("#OwnerAgency").append(opt);
});
How do i set the selected default to be the blank option.
html:
<div class="SmallTopSpace">
<span class="LabelNormal">Primary Case Agency</span>
#Html.DropDownListFor(m => m.Agencies.AgencyKey, new SelectList(""), "", new { #class = "ImportDropDownMax", #id = "OwnerAgency", #onchange = "OwnerAgencyFunction();" })
</div>
before the $.each just append at that start of the data array another empty element .
or in your html do :
<select>
<option disabled selected></option>
</select>
Can't you just insert an empty option at the top in your view/html?
<select id="OwnerAgency">
<option></option>
</select>
Or you can add it in javascript.
var emptyOption = true;
$.each(data, function (value, key) {
var opt;
if (emptyOption) {
opt = "<option></optino>";
$("#OwnerAgency").append(opt);
emptyOption = false;
}
opt = "<option value=\"" + key + "\">" + value + "</option>";
$("#OwnerAgency").append(opt);
});
<select id="mySelect">
</select>
script:
var myOptions = {
val1 : 'text1',
val2 : 'text2'
};
var mySelect = $('#mySelect');
$.each(myOptions, function(val, text) {
mySelect.append(
$('<option></option>').val(val).html(text)
);
});
mySelect.append('<option value=' + myOptions.length + ' selected>default</option>');
set your default select before or after select list generation http://jsfiddle.net/3ns3fj3t/
in your case:
$.each(data, function (value, key) {
var opt = "<option value=\"" + key + "\">" + value + "</option>";
$("#OwnerAgency").append(opt);
});
$("#OwnerAgency").append('<option value=' + data.length + ' selected>default</option>');
You could do it in your C# ViewModel by adding an empty element to SelectList object:
var selectList = new SelectList(....);
selectList.Items.Insert(0, new ListItem(String.Empty, String.Empty));
selectList.SelectedIndex = 0;