I'm hoping you can please help.
I have the following HTML code:
<select id='bonus1frequency'>
<option value="0">Annual</option>
<option value="1">Half Yearly</option>
<option value="2">Quarterly</option>
</select>
Depending on what option is selected, fields are displayed in a divider. For example if you select annual, a field to enter annual bonus is displayed. If you select 'Half Yearly' two fields to enter two half yearly bonuses are displayed.
The trouble I'm having is that if you select 'Half yearly' for example, then enter what the half yearly bonus into the fields, then you change your mind and decide you want to enter an annual bonus instead, the values that you enter into the half yearly bonus are retained. I need them to be set to zero when you switch between options in the html select box.
I tried the following code to help with this but it's not working and i'm not sure why. All it does is prevent me from putting anything at all into the half year boxes.
var bonus_val_1 = document.getElementById("bonus1frequency");
var strUser = bonus_val_1.options[bonus_val_1.selectedIndex].value;
if (strUser = "0") //if annual bonus is selected
{
document.getElementById("halfyear_bonus_one").value = 0.00;
}
Edit:
I'm using the following JQUERY in the main HTML document to actually switch what fields are displayed when the user selects each option. So if the user selects option value 0 'annual' in the select box, the following code will show the annual bonus divider containing the annual bonus field, and hide the dividers that show half yearly and quarterly bonus fields.
Based on comments about how I need to tie resetting these fields to the change event, I just thought maybe I can reset the fields to zero within the following jquery code. However I'm even less familiar with JQUERy and not sure how to do that...any help would be much appreciated.
$('#bonus1frequency').on('change', function() {
if ( this.value == '0')
//.....................^.......
{
$("#annual").show();
$("#halfyearly").hide();
$("#quarterly").hide();
}
if ( this.value == '1')
//.....................^.......
{
$("#annual").hide();
$("#halfyearly").show();
$("#quarterly").hide();
}
EDIT 2
I have updated the code as follows:
$('#bonus1frequency').on('change', function() {
if ( this.value == '1')
//.....................^.......
{
$("#annual").show();
$("#halfyearly").hide();
$("#quarterly").hide();
$("#halfyear_bonus_one").val("0");
This prevents me from entering a value into the halfyear bonus one field. It just keeps resetting the value to zero. I've added an empty 'choose' option to the select box but it hasn't made a difference. Any ideas?
Please refer following for help and add code for quarterly. Use jquery instead of using javascript code to get elements.
<select id="bonus1frequency">
<option value="0">Annual</option>
<option value="1">Half Yearly</option>
<option value="2">Quarterly</option>
</select>
<div id="annual" style="display: none;">
<input type="text" id="a1">
</div>
<div id="half" style="display: block;">
<input type="text" class="b2">
<input type="text" class="b2">
<script>
$('#half').hide()//Same as this hide quarterly div
$("#bonus1frequency").change(function(){
var strUser = $(this).val()
if (strUser === "0") //if annual bonus is selected
{
$('#annual').show()
$('#half').hide()
$(".b2").val(0);
}else{
$('#half').show()
$('#annual').hide()
$('#a1').val(0)
}
})
</script>
</div>
The problem with your code is that you're not binding it to the select's change event. It will run when loading the page, and since the default option in the dropdown is "Annual", the value which will appear as the value of #halfyear_bonus_one would be 0.00 and won't change, even if the user will choose another option in the dropdown.
You should create a js function which contain your code (with few corrections)
and then bind it to a change event of the dropdown.
Moreover, you should add conditions to handle the other scenarios: "half yearly" and "quarterly".
var bonusval1 = document.getElementById("bonus1frequency");
bonusval1.onchange = function () {
var strUser = bonusval1.options[bonusval1.selectedIndex].value;
if (strUser == "0"){ //if annual bonus is selected
document.getElementById("halfyear_bonus_one").value = "0.00";
} else if(strUser == 1){ //Half yearly is selcted
document.getElementById("halfyear_bonus_one").value = "1.00";
} else { //quertly is selected
document.getElementById("halfyear_bonus_one").value = "2.00";
}
}
Now, there's another problem - the default value is the first value - but the "onchange" event won't trigger. We can run the function outside of the onchange event in order to handle the default value or you can add a blank option to the dropdown as the first option, something like "Choose:" or whatever.
Jsfiddle
Regarding the second question
I didn't understand why would you use jQuery all of a sudden when you already
wrote pretty good js code. Those kind of decisions should be considered in the beginning of the process.
Anyway, You can use the .val() function to change the value of the input fields. I don't have the code of your form and the dividers but it should be pretty much like the following:
if ( this.value == '0')
//.....................^.......
{
$("#annual").show();
$("#halfyearly").hide();
$("#quarterly").hide();
$("#id_of_input_for_halfyearly").val("0");
$("#id_of_input_for_quarterly").val("0");
}
I think this will help you out.
jQuery('#bonus1frequency').on('change',function(){
if(this.value==1){
jQuery('.yearly').val('').show();
jQuery('.half-yearly').val(0).hide();
jQuery('.quarterly').val(0).hide();
}else if(this.value==2){
jQuery('.yearly').val(0).hide();
jQuery('.half-yearly').val('').show();
jQuery('.quarterly').val(0).hide();
}else if(this.value==3){
jQuery('.yearly').val(0).hide();
jQuery('.half-yearly').val(0).hide();
jQuery('.quarterly').val('').show();
}
})
Check this Demo
Related
UPDATE
I am working on SharePoint and Nintex Form which allows embedding JS into the form but uses NWF$ instances e.g. (NWF$('#' + varConcept) see an example here Javascript - How to hide a drop down control if it's empty
I have now created a question in the sharepoint section
There is a fieldname (not a dropdown) named varConcept and may contain values such as Pending, In Review, Accepted, In Work.
There is a dropdown menu named varConcept which holds following options: Updated, Reviewed, Already Implemented, Duplicate, Assigned and the idea behind all this is to make a script that checks the varStatus and shows relevant options in the dropdown box aka. varConcept.
In simple context:
IF varStatus contains "Pending" then show varConcept options Updated and Duplicate
IF varStatus contains "In Review" then show varConcept options Reviewed and Already Implemented
IF varStatus contains "Accepted" then show varConcept options Assigned
else hide everything
You can generate the dropdown using javascript and based on the status you create the dropdown options.
var currentStatus = 'Reviewed'; // load the current status of the dropdown
var div = document.querySelector("#container"),
frag = document.createDocumentFragment(),
select = document.createElement("select");
if (currentStatus === 'Accepted') {
select.options.add(new Option("Rejected", "Rejected"));
} else if (currentStatus === 'Reviewed') {
select.options.add(new Option("Accepted", "Accepted", true, true));
select.options.add(new Option("Rejected", "Rejected"));
} else if (currentStatus === 'Rejected') {
select.options.add(new Option("Accepted", "Accepted", true, true));
}
frag.appendChild(select);
div.appendChild(frag);
<div id="container">
</div>
You could add a "onchange" event to the select.
When the selection changes, you can hide/show options as you wish. This can be done based on the selected value.
const filterOptions = (e) => {
const selectedValue = e.options[e.selectedIndex].value;
for(const option of e.options){
option.classList.remove('hidden');
}
// always hide the initial "select one" option
e.options[5].classList.add('hidden');
if(selectedValue === 'pending'){
e.options[1].classList.add('hidden');
e.options[3].classList.add('hidden');
e.options[4].classList.add('hidden');
}
}
.hidden{
display: none;
}
<select name="" id="dropdown" onchange="filterOptions(this)">
<option value="pending">Pending</option>
<option value="accepted">Accepted</option>
<option value="reviewed">Reviewed</option>
<option value="rejected">Rejected</option>
<option value="already_done">Already Done</option>
<option id="initial" selected >Select one</option>
</select>
Yes, you can do that. Since your question is not completed with information like what is Status and how we are getting the value of Status.
Let us assume you are getting the value of Status from some API you build and your HTML is below
<ul>
<li class="myClass" id="accepted">Accepted</li>
<li class="myClass" id="reviewed">Reviewed</li>
<li class="myClass" id="rejected">Rejected</li>
<li class="myClass" id="already-done">Already Done</li>
<ul>
Step 1: Using CSS hide all the elements of your dropdown.
Example:
.myClass{
display: none;
}
Step 2: Now lets use JavaScript to show and hide elements based on Status variable value.
switch(Status) {
case "Pending":
document.getElementById("reviewed").style.display = "block;
break;
case "Accepted":
document.getElementById("accepted").style.display = "block;
break;
case "Rejected":
document.getElementById("rejected").style.display = "block;
break;
case "Already Done":
document.getElementById("already-Done").style.display = "block;
break;
}
After many trial and errors, I got it working
NWF$(document).ready(function() {
if (NWF$('#' + varStatus).val() == 'Pending' )
{
NWF$("#"+ varConcept).find("option[value='Pending']").remove();
NWF$("#"+ varConcept).find("option[value='Reviewed']").remove();
}
if (NWF$('#' + varStatus).val() == 'In Review' )
{
NWF$("#"+ varConcept).find("option[value='Pending']").remove();
NWF$("#"+ varConcept).find("option[value='Updated']").remove();
}
});
There is no other else if to say "anything outside the above, hide everything" but if you have the answer, feel free to add a comment.
Well, I know everyone is giving you code options, because you did ask about code, but honestly, since this is in SharePoint with a Nintex Form, you can do this entirely without code.
Create a List in SharePoint that contains two columns. One column for the test values (pending, in review, accepted) and a second column for the answers (updated, reviewed, duplicate, assigned).
On the form, add a List Lookup control. Use the Filter section to point it to your varStatus control.
I have this HTML:
<select id="categories">
<option value="category1">Category 1</option>
<option value="category2">Category 2</option>
</select>
<input type="search" id="search" placeholder="Search here" autofocus>
And this jquery:
var categories = $("#categories option:selected").val();
var search = $("#search");
if (categories = "category2") {
search.attr("placeholder", "Search for category 2");
} else {
search.attr("placeholder", "Search for category 1");
}
I'm trying to put a different placeholder according to the selected value, but no matter what is selected, it always show the first placeholder. This might seem silly, but further I want to be able to pick the value of the selected option to make the search in that specific category, kinda like the Amazon website.
I have used == to compare, but nothing happens, the placeholder stays with "Search here".
PS: With this code running, using the console on Chrome, if I type and execute categories it will always show in the console category2, no matter which one is selected, but if I type and execute $("#categories option:selected").val();, then it will show the selected value. I tried to put this directly inside the if in the code, but returned the same problem. I also tried to replace the else for if (categories = "category1"), but then it was the same problem, but this time the placeholder showed was always the second one.
//you should add an onChange event,like this:
$("#categories").change(function(e){
var categories = e.target.value;
if (categories == "category2") {
...
} else {
...
}
})
I am in the process of building an e-Commerce shop and have hit a small bump in the road for my actual product page. Based on any product options set that would add to the price if selected, I would like to be able to update the price on the page live when these options have been added. I have managed to iterate through every element with a "data-price-effect" attribute attached to them, HOWEVER, when it comes to a select element, I would need to check if the item is selected as an option, each option has their respective price change attribute of course, but the value would only update to the actual select element.
Here is my code upto now:
function updatePrice(){
$('[data-price-effect]').each(function( index ) {
// do something
});
}
Basic HTML set-up to explain further:
<form>
<input type="text" name="foo" onchange="updatePrice();" data-price-effect="10.00" />
<select name="bar" onchange="updatePrice();">
<option selected value="Item1" data-price-effect="5.00">Item 1</option>
<option selected value="Item2" data-price-effect="8.00">Item 2</option>
<option selected value="Item3" data-price-effect="10.00">Item 3</option>
</select>
</form>
I have NO idea how to even logically do this, not even with some huge messy code. Any pointers here from someone more experienced with Javascript?
Instead of having "updatePrice()" on each element, you could have a listener for all form elements for the function:
var EffectElements = $('form input[data-price-effect], form select');
EffectElements.on('change', function() {
var PriceEffect = 0;
EffectElements.each(function() { // Loop through elements
if ($(this).is('select')) { //if this element is a select
$(this).children().each(function() { //Loop through the child elements (options)
if ($(this).is(':selected')) { //if this option is selected
PriceEffect += parseFloat($(this).attr('data-price-effect'));
}
});
} else {
PriceEffect += parseFloat($(this).attr('data-price-effect'));
}
});
});
You could then use the PriceEffect variable to update your price on the website.
Ultimately it's the IS function doing the dirty work you needed ~_o
Working Example
I have one html form - On that one text field like
<input type = "text" name = "age" value = "" id = "txt_age">
On the value of age i have to show this element like -
<select name = "married">
<option value = "Yes">Yes</option>
<option value ="No">No</option>
</select>
If age>18 then married field will be shown to form otherwise hide it.This age>18 condition is stored in database.As value of age changes married field toggle(show/hide).
How can i do it with javascript/jquery.Please suggest.
For more information, all these fields are genereated dynamically.So i was thinking to add onchange = "somefuction(condition);" with age while creating then look for field are to be shown when condition is satisfied, is also in DB.
OR
One solution may i think that -
The field in this case married will look for value of age changes.Then accordingly married will hide/show itself.But problem is that how married observe age field or call javascript function.
Sorry for not explaining full problem.
add id="married" to the select and use something like this.
$("#txt_age").blur(function() {
if(parseInt($(this).val() > 18) {
$("#married").show();
} else {
$("#married").hide();
}
});
Try this & note
avoid the space between id = "txt_age"
rest this should help:
var $foo = $('select[name="married"]');
$foo.hide(); // in start always hide
$('#txt_age').on('blur', function() {
if(parseInt(this.value)>18){
$foo.hide();
} else {
$foo.show();
}
});
I'm somewhat new to jQuery. I'm pretty sure this is possible, but I'm not quote certain how to code this.
What I'm looking to do is to use a dropdown with selections that represent ranges (e.g. if someone were searching for bedrooms, the dropdown selctions would look like "0-2", "3-5", "6+"). Then when someone chooses a selection, two hidden fields would by dynamically filled. One field with the minimum of the range, and the other field with the maximum of the range.
Here is an example of how I'm trying to structure this:
<select id="bedrooms" class="dropdown">
<option>Bedrooms</option>
<option></option>
<option value="1">0-2</option>
<option value="2">3-5</option>
<option value="3">6+</option>
</select>
<input type="hidden" name="bedrooms-from" value=''>
<input type="hidden" name="bedrooms-to" value=''>
I suppose the values of each option could change, I wasn't sure what the best way to approach that would be.
I haven't actually run this, but I think it should work:
$("#bedrooms").change(function ()
{
// Get a local reference to the JQuery-wrapped select and hidden field elements:
var sel = $(this);
var minValInput = $("input[name='bedrooms-from']");
var maxValInput = $("input[name='bedrooms-to']");
// Blank the values of the two hidden fields if appropriate:
if (sel.val() == "") {
minValInput.val("");
maxValInput.val("");
return;
}
// Get the selected option:
var opt = sel.children("[value='" + sel.val() + "']:first");
// Get the text of the selected option and split it on anything other than 0-9:
var values = opt.attr("text").split(/[^0-9]+/);
// Set the values to bedroom-from and bedroom-to:
minValInput.val(values[0]);
maxValInput.val((values[1] != "") ? values[1] : 99999999);
});
$("select").on("change", function() {
$("form").append( /* <input type='hidden'> tag here */ );
});