How to remove an element on click - javascript

I need to remove the existing html when the selectbox val == 0. Here is my HTML,
<div class="info-cont">
<ul class="map-list">
<li>
<span class="left">
<label>Name 1</label>
</span>
<span class="right">
<select class="combo">
<option selected="selected" value="0"></option>
<option value="1">F name</option>
<option value="2">M name</option>
<option value="3">L name</option>
</select>
</span>
</li>
</ul>
</div>
Note : There are about 10 selectboxes in my page like the above,
and jquery for the above is,
$(document).ready(function () {
$('#save').click(function () {
var comboLength = $('.combo').length;
var selectedLength = $('.combo option:selected[value!=0]').length;
if (comboLength == selectedLength) {
alert('Thanks all the fields are selected');
return false;
}
if ($('.combo option:selected[value==0]')) {
$("div.info-cont ul.map-list li span.right").append("<br>Please select an appropriate value").addClass('validerror');
} else {
$("div.info-cont ul.map-list li span.right").html("");
$("div.info-cont ul.map-list li span.right").removeClass('validerror');
}
return false;
})
});
What i need to do in the else condition?(My else part is not funct). Also when i click the submit button for the second time, I should not append a html to which i already received in my first click. Any help? Thanks...

Change the if to
if($('.combo option:selected').val() === '0'){
All issues can be resolved with
$(document).ready(function(){
$('#save').click(function(){
var combo = $('.combo'), // get all combo elements
selected = $('.combo').filter(function(){
return $(this).find('option[value!="0"]:selected').length;
}), // get all valid combo elements
unselected = combo.not(selected); // get all non-valid combo elements
// clear previous error messages
combo
.closest('.right') // find containing .right element
.removeClass('validerror') // remove error class
.find('.errormessage') // find error message
.remove(); // remove error message
// chech if all combos are valid
if (combo.length === selected.length) {
alert('Thanks all the fields are selected');
return false;
}
// highlight non-valid elements
unselected
.closest('.right')
.addClass('validerror')
.append('<div class="errormessage">Please select an appropriate value</div>');
return false;
});
});
demo at http://jsfiddle.net/gaby/Y3RrH/

Related

How to check multiple select fields if something is selected

I do have a form with a variable amount of dropdowns I want to check, if something is selected before submit.
What I have is this javascript, but it works for the 1st dropdown only.
var ddl = document.getElementById("status");
var selectedValue = ddl.options[ddl.selectedIndex].value;
if (selectedValue == "")
{
alert("Machine status must be selected");
return false;
}
for this dropdown (this comes from a loop so I have a variable amount of them within the form)
<select name="mstatus[]" id="status">
<option value="">please select</option>
<option value="status1">ok</option>
<option value="status2">not ok</option>
</select>
Any hint in the right direction, much appreciated. thanks
I would suggest giving the selects you wish to iterate through the same class and use Jquerys .each(). https://api.jquery.com/each/
For the validation I would use a data tag to help you with the alert label
<select class="form-select" data-label="Machine status"></select>
Then the JS code
$('.form-select').each(function(index, element) {
let value = $(element).val();
let label = $(element).data("label");
if (value === "") {
alert(`${label} status must be selected`);
return false;
}
});
Without Jquery you could do.
document.querySelectorAll('.form-select').forEach(function (element, index) {
//do same code here
});

Show/hide depending on dropdown menu selection

So I have a dropdown menu. The id for this dropdown menu is "courses". This dropdown also has an additional attribute, onclick="displayField();
The dropdown has 2 options.
2 and 3.
Now, I want everything with the class rsform-block-cotecours1 to be hidden depending on which option is chosen.
Here is the JavaScript for that:
function displayField()
{
if(document.getElementById("courses").text == '2';)
document.getElementsByClassName('rsform-block-cotecours1').style.display="none";
if(document.getElementById("courses").text == '3';)
document.getElementsByClassName('rsform-block-cotecours1').style.display="";
}
window.addEvent('domready', function() {
displayField();
});
However, this doesn't work, and I don't know why.
Is this what you are looking for?
Fiddle: fiddle
<select id="courses" onchange="ddlChange()">
<option value="2">2</option>
<option value="3">3</option>
</select>
JavaScript
function ddlChange() {
if (document.getElementById("courses").value =="2"){
document.getElementsByClassName('rsform-block-cotecours1')[0].style.display="none";
alert(document.getElementById("courses").value );
}
if (document.getElementById("courses").value == "3"){
document.getElementsByClassName('rsform-block-cotecours1')[0].style.display="block";
alert(document.getElementById("courses").value );
}
}
Change the code to following and test
function displayField()
{
if(document.getElementById("courses").value == '2';)
document.getElementsByClassName('rsform-block-cotecours1')[0].style.display="none";
if(document.getElementById("courses").value == '3';)
document.getElementsByClassName('rsform-block-cotecours1')[0].style.display="";
}
window.addEvent('domready', function() {
displayField();
});
in case you want to access the ext and not the value of dropdown list in javascript, then use following code to access the text of selected option from drop down
var courseElement = document.getElementById("courses");
var text = "";
if (courseElement.selectedIndex != -1)
{
text = courseElement.options[courseElement.selectedIndex].text;
}

jquery change function hide and show div

have this code, i want to convert it to be able to allow the user to pick ANY possible select and have div [id='setprice'] show up or something to that effect. currently i have 4 options, but it could be up to 10+ depends on how many are in the database. but it shouldn't matter, i just want which ever gets selected to open the setprice div. Thanks.
$("#category").change(function () {
$("#setprice").hide();
if ($(this).val() == "cow") { $("[id='setprice']").show(); }
else if ($(this).val() == "dog") { $("[id='setprice']").show(); }
else if ($(this).val() == "monkey") { $("[id='setprice']").show(); }
else if ($(this).val() == "kungfoo") { $("[id='setprice']").show(); }
});
HTML
<select id="category">
<option value=''>Select</option>
<option value='cow'>Cow</option>
<option value='dog'>Dog</option>
<option value='monkey'>Monkey</option>
<option value='kungfoo'>kungfoo</option>
</select>
<div id='setprice'>this is hidden onload, then shows on any #category selection</div>
Seems to be alot of cofusion in what im asking, These options i've given are random names, the categories that are going to be loaded, are from a database and more could be added depending how it expands, so i want the script to not show div=setprice, but when anything gets selected in #category to open setprice.
You will need to call the function only when the value of the select box isn't empty.
$("#category").change(function () {
$("#setprice").toggle(!!this.value);
});
Here is a working fiddle.
This is the cleanest you will get this.
DEMO
$("#category").change(function () {
$("#setprice").toggle(!!this.value);
});
The $("#setprice").toggle(!!this.value); is just a way to use a boolean inside the .toggle() method,
otherwise you do it equally like:
var $setPriceEl = $("#setprice");
$("#category").change(function () {
$setPriceEl.hide(); // hide by default
if(this.value) $setPriceEl.show(); // show only if has value
});
or even:
$("#category").change(function () {
$("#setprice")[this.value ? "show" : "hide" ]();
});
Please find the answer below ...
HTML :
<select id="category">
<option value=''>Select</option>
<option value='cow'>Cow</option>
<option value='dog'>Dog</option>
<option value='monkey'>Monkey</option>
<option value='kungfoo'>kungfoo</option>
</select>
<div id='setprice' style="display:none;">this is hidden onload,
then shows on any #category selection</div>
JQUERY :
$(document).ready(function(){
$("#category").change(function() {
$("#category option:selected" ).each(function() {
var str = $( this ).text();
if(str == "Select"){
$("#setprice").hide();
}else{
$("#setprice").show();
$("#setprice").text(str);
}
});
}).trigger("change");
});

change selected option of dropDown using jQuery

I have a dropdown on change a popup appears with a warning that change the value will do some affects. when user select no the dropdown selected index is supposed to return to initial selected option. here is what I do:
function closeDeleteVariantsPopup(){
parent.$.fn.colorbox.close();
var elementSpecies= parent.document.getElementsByClassName("speice");
for(var i = 0;i<elementSpecies[0].options.length; ++i) {
alert(parent.document.getElementById("speciesHiddenValue").value);
if(elementSpecies[0].options[i].id === parent.document.getElementById("speciesHiddenValue").value) {
alert(parent.document.getElementById("speciesHiddenValue").value);
elementSpecies[0].selectedIndex = i;
break;
}
}
}
html & freemarker:
[#spring.bind "genomicReferenceBean.specie.id"/]
<select name="specie.id" id="specie.id" [#if !(genomicReferenceBean.specie?has_content) || genomicReferenceBean.specie.id==-1] multiple="multiple" [/#if] class='speice singleList' onchange='getMaterials()' >
[#if genomicReferenceInitializerBean.species?has_content]
[#list genomicReferenceInitializerBean.species as initializerValueBean]
<option for="selectSpecie" name="${initializerValueBean.name}" [#if genomicReferenceBean.specie?has_content && genomicReferenceBean.specie.id?number == initializerValueBean.id] selected="selected" [/#if] value="${initializerValueBean.id}">${initializerValueBean.name}</option>
[/#list]
[/#if]
</select>
<input type="hidden" id="speciesHiddenValue" value="${genomicReferenceBean.specie.id?number}"/>
now when I press no button the popup close and nothing happen
I used jQuery and it worked fine:
parent.$(".speice option").each(function(){
if($(this).val() === parent.document.getElementById("speciesHiddenValue").value) {
$(this).attr('selected', 'selected');
}
});

how to add same onchange events to different select boxes

I want to add 'change' events to 4 select boxes. I have done it using bind().
But I want to call different functions on change of each select box.
Say function1() on change event of SelectBox1...
How should I do it?
I am new to javascript & jquery, so please help.
Thank you
Suppose your HTML like this:
HTML
<select id="selectBox1">
</select>
<select id="selectBox2">
</select>
<select id="selectBox3">
</select>
<select id="selectBox4">
</select>
jQuery
$('select[id^=selectBox]').on('change', function() {
// to get the id of current selectBox
var selectId = this.id;
if(selectId == 'selectBox1') {
function1();
} else if(selecId == 'selectBox2') {
function2();
}
// and so on
});
Some more
$('select[id^=selectBox]').on('change', function() {
// to get the selected value
var value = $.trim( this.value ); // $.trim() used to remove space
// from beginning and end
// you may not use
// to get selected option text
var optText = $('option:selected', this).text()
// to get the selectedIndex
var selIndex = this.selectedIndex;
// OR
var selIndex = $(this).prop('selectedIndex');
});
Note
Here, select[id^=selectBox] get select boxes, whose id start with selectBox. You may have something different id.
.change() used for bind the event to those select box.
Read more about
jQuery selectors
jQuery Events
$.trim()
.prop()
you can set an specific attribute for each select so:
<select id="selectBox1" val='1'>
</select>
<select id="selectBox2" val='2'>
</select>
<select id="selectBox3" val='3'>
</select>
<select id="selectBox4" val='4'>
</select>
and then bind onchange event like this:
$("select").change(function(){
var val = $(this).attr("val");
if (val == '1')
{
//logic for first select change
}
else if (val == '2')
{
//logic for second select change
}
else if (val == '3')
{
//logic for third select change
}
// and so on...
});
hope that helps.

Categories