get selected value from drop down - javascript

I want to change the zip code according to drop down list for example if i select Canada from drop down list name "ddlselcountry" and Canada is at 40th place in drop down, for that only zip code should change (what is the condition i should put in for 'if condition') and for other country it should go to else condition.
I have tried this in upper example but i am not going inside if condition,It is generating error.
if ($("#ddlselcountry")[0].selectedindex == "40"){
var zipCodePattern = /^[A-Za-z0-9]{3}[ ]{1}[A-Za-z0-9]{3}$/;
return zipCodePattern.test(zipcode);
}

It is selectedIndex not selectedindex. It is case sensitive.
$("#ddlselcountry")[0].selectedIndex
Instead of this you can use
$("#ddlselcountry").val() == 'value of canada';

Please change selectedindex to selectedIndex
$("#ddlselcountry").selectedIndex

U can try this
if ($("#ddlselcountry").selectedIndex == "40"){
var zipCodePattern = /^[A-Za-z0-9]{3}[ ]{1}[A-Za-z0-9]{3}$/;
return zipCodePattern.test(zipcode);
}

Related

javascript add value to id based on select option value conditional

First off, I know I should know this. I am just not connecting the dots.
I have jquery working with a select menu so that when an option is selected, it's value is added to a hidden id in my form.
What I need, is that when an option is selected in this same select menu, depending on which option is selected, an email becomes the value in a different hidden id in the form.
I have an if conditional in my jsfiddle but it is not working. Any help is appreciated. Thanks! Peter T
jQuery(document).ready(function() {
// pass the title of the selected topic option to a hidden 'topic' form field
jQuery('select#recipient_email').change(function() {
var topic = jQuery('select#recipient_email option:selected').attr('title')
// set the hidden input's value
jQuery('#college2').val(topic);
//var topic_var = jQuery('#college2').val(topic);
if ((jQuery('#college2').val(topic)) == "Var 1")
{
$("#recipient_email_user").val("John.Doe#mail.com");
}
if ((jQuery('#college2').val(topic)) == "Var 2")
{
$("#recipient_email_user").val("Jane.Doe#mail.com");
}
})
})
jsfiddle
This line is wrong
if ((jQuery('#college2').val(topic)) == "Var 1")
You are setting the value and it returns the jQuery object, it is the equivilant of jQuery('#college2') == "Var 1"
If should just be
if (topic == "Var 1")

Hide drop-down box on basis of text result using javascript

I want to hide a drop-down on the basis of a selected user input.
So far I have done
var getText = document.getElementById('issuemeters-issuance_type').value;
Then in if else condition
if(getText == 'HESCO/OEM')
{
$('.field-issuemeters-issuer').hide();// the drop-down which i want to hide
$('#issuemeters-issuer').val('');// setting the text value to null
}
else
{
$('.field-issuemeters-issuer').show();
}
It will work when getText is equal to HESCO/OEM. I have also checked the value in console but I don't know why it's not working.
Any help would be highly appreciated.
try with a listener on "issuemeters-issuance_type" change:
$('#issuemeters-issuance_type').on('change',function(){
if($(this).val() === 'HESCO/OEM')
{
$('.field-issuemeters-issuer').hide();// the drop-down which i want to hide
$('#issuemeters-issuer').val('');// setting the text value to null
}
else
{
$('.field-issuemeters-issuer').show();
}
});
assuming that "issuemeters-issuance_type"

Javascript catch unselected radio button along with textboxes and alert

I'm practically new here and i'm a beginner in programming.
I am creating an html/js based template for my team for easy consolidation of data and copy to clipboard so we can easily paste it in our main tool.
The problem is that doesn't seem to work properly (at least here at the office, at home it does work).
It doesn't prompt when the radio selection is empty, so I am resorting to using my current function that catches any textboxes/textarea that is empty. (sample code below)
if (document.getElementById('INbrief').value == "") {
errCatch +="-Issue/Request \n";
valid = false;
}
if (document.getElementById('INdesc').value == "") {
errCatch +="-Issue/Request Description \n";
valid = false;
}
if (!valid) {
document.body.removeChild(dummyTxtArea);
alert(errCatch);
return valid;
} else {
document.body.removeChild(dummyTxtArea);
alert ("Data has been copied to Clipboard.");
}
The above if else is inside a Function that is called when the Evenlistener is triggered via "click" of the submit button. I tried inserting a 'for' statement above the if else inside the function but it wont work and the alert will only show that the textbox/area are empty. Thanks in advance for your help
Your code was throwing errors at lines 4 and 5 when you were trying to get the value of an unchecked radio box and set the variable to that value:
var selectedLOB = document.querySelector('input[name="INlob"]:checked').value; //LOB selected
var selectedSev = document.querySelector('input[name="INsev"]:checked').value; //Severity selected
In order to fix this you must first check if the radio is selected, and then if it is get the value that is selected. You can do that by replaceing your lines 4 and 5 with the following:
var selectedLOB = document.querySelector('input[name="INlob"]:checked') ? document.querySelector('input[name="INlob"]:checked').value :false;
var selectedSev = document.querySelector('input[name="INsev"]:checked') ? document.querySelector('input[name="INsev"]:checked').value :false;
This code will first check to see if the radio is checked, if it is it will set the variable to the value, if it is not it will set the variable to false.
(The a ? b : c is know as the conditional or ternary operator and is just a short if() else()statement). This change will stop the errors from being thrown.
You will also need to update your checks further down for the radios to:
if (selectedLOB == false) {
errCatch +="-Choose LOB \n";
valid = false;
}
if (selectedSev == false) {
errCatch +="-Choose Severity \n";
valid = false;
}
As a side note you don't have to set uncheck radios to false, you could set them to a string like 'unchecked' or ''empty' if it helps make your code more readable. Just be sure to make sure that your checks match what you set it to.

javascript condition for session storage not working as expected

Currently working on session storage where user have to select one radio button from the first page and click next button div has to show in the second page in the first page i have created a function with set of objects where the data will be stored using set item in the second i am trying to get those value using get item.
I have two scenarios
When the user select pg radio button from the first radio group and if any location like alain / abudhabi if user select alain | abudhabi from the location from location then user slect DIP EDU if user click submit button then in the second page i need to get one check box and create application button the rest should be hide -- With my code this was working
If the user select ug radio button from the first radio group and if any location like alain / abudhabi if user click submit button then in the second page I need to get Just a Pay button but this was not working kindly help me
Here is my plunker link just like fiddle
This is what my code for to get the item from the first page
function storedata(){
var storeDate = {};
storeDate['storedValue1'] = $('input[id=pg]:checked').val();
storeDate['storedValue2'] = $('#alain').prop('checked'),$('#abudhabi').prop('checked');
storeDate['storedValue3'] = $('#slt_mjrpg option:selected').val("Dip - Prof. PG Dip in Teaching");
sessionStorage.setItem('storeDate', JSON.stringify(storeDate));
}
function storedata1(){
var storeDate1 = {};
storeDate1['storedValuej'] = $('#slt_mjr option:selected').val("Bachelor of Arts in Persian").text();
sessionStorage.setItem('storeDate1', JSON.stringify(storeDate1));
console.log(storeDate1);
}
When i checked in session storage I am getting the storedValue2 as false
After providing or in this line
storeDate['storedValue2'] = $('#alain').prop('checked') || $('#abudhabi').prop('checked');
I am getting true in the storedValue2 = true but my output was not working as expected
In the second page
var otherObj = JSON.parse(sessionStorage.getItem('storeDate'));
var otherObj1 = JSON.parse(sessionStorage.getItem('storeDate1'));
if (otherObj.storedValue1 && otherObj.storedValue2 && otherObj.storedValue3 != "pg") {
$(".pay_check,.pay_click").show();
$(".pay_trans").hide();
} else if (otherObj1.storedValuej === "BAP") {
$('.create_btn,.no_applica').show();
$('.pay_btn').hide();
} else { * * // I have tried using like this but no use**
//$('.create_btn,.no_applica,.pay_click').hide();
$('.pay_btn').show();
}
any suggestion guys for the question
Kindly please guide me where I am doing wrong. Thanks in advance
Okay so you have a number of problems here. Mostly due to a misunderstanding of functions.
First of all, we can change
storeDate['storedValue1'] = $('input[id=pg]:checked').val();
// to
storeDate['storedValue1'] = $('#pg').val();
The $ function provided by jQuery selects elements based on a given selector. So $('#pg') selects the element with the id pg. Then val() returns the value of the element.
Secondly, we need to change
storeDate['storedValue2'] = $('#alain').prop('checked'),$('#abudhabi').prop('checked');
// to
storeDate['storedValue2'] = $('#alain').prop('checked') || $('#abudhabi').prop('checked');
You're just misunderstanding boolean operators here. a || b resolves to true if a or b resolves to true.
And finally the worst offender
storeDate['storedValue3'] = $('#slt_mjrpg option:selected').val("Dip - Prof. PG Dip in Teaching");
// to
storeDate['storedValue3'] = $('#slt_mjrpg).val();
val returns the value of an element. In the case of a select, it will return the value of the selected option. Providing a string parameter will set the value. So what we're doing instead is just getting the value, and we'll check the value later.
In your hide/show function, we don't need to change very much. We're just going to move that inappropriate val parameter down here in an equality operation to get a boolean value.
if (otherObj.storedValue1 && otherObj.storedValue2 && otherObj.storedValue3 === "Dip - Prof. PG Dip in Teaching")
i think session storage is working with only one page.
You should try localstorage instade of sessionstorage.
Try this
function storedata(){
var storeDate = {};
storeDate['storedValue1'] = $('input[id=pg]:checked').val();
storeDate['storedValue2'] = $('input[id=alain]:checked').val();
storeDate['storedValue3'] = $('#slt_mjrpg option:selected').val("Dip - Prof. PG Dip in Teaching");
localStorage.setItem('storeDate', JSON.stringify(storeDate));
}
and
var otherObj = JSON.parse(localStorage.getItem('storeDate'));
var otherObj1 = JSON.parse(sessionStorage.getItem('storeDate1'));
if (otherObj.storedValue1 && otherObj.storedValue2 && otherObj.storedValue3 !="pg") {
$(".pay_check,.pay_click").show();
$(".pay_trans").hide();
} else if (otherObj1.storedValuej === "BAP"){
$('.create_btn,.no_applica').show();
$('.pay_btn').hide();
} else {
**// I have tried using like this but no use**
//$('.create_btn,.no_applica,.pay_click').hide();
$('.pay_btn').show();
}

How to select from option menu in javascript

I need to be able to change certain option from select menu to be as default (start) value when I do something.
For example when I declare it, English language is default value.
How to change that with the code and not with the click.
<form id="form1" name="form1" method="post" action="">
<select name="websites1" id="websites1" style="width:120px" tabindex="1">
<option value="english" selected="selected" title="images/us.gif">English</option>
<option value="espanol" title="images/es.gif">Espanol</option>
<option value="italian" title="images/it.gif">Italiano</option>
</select>
</form>
In the body tag I have declared:
<script type="text/javascript">
$(document).ready(function() {
$("body select").msDropDown();
});
</script>
I am using this SCRIPT
I have tried all of the bellow examples and none this is good for me.
What else can I do change default select value.
This is working for me as mentioned in the docs:
$('#websites1').msDropDown().data('dd').set('selectedIndex',2);
This will select italian ;)
/edit:
Keep in mind that #Patrick M has a more advanced approach and he posted his approach before I posted mine ;)
If you are having weird css issues like I did, try this undocumented stuff:
$('#websites1_msa_2').click(); // this will also select the italian
As you can see the id is generated by $('#websites1_msa_2') the id of the selectbox plus the $('#websites1_msa_2') index of the option item.
A bit hacky but works ;)
So you could then define a JavaScript-Function like this:
var jQueryImageDD_selectByName = function(name) {
var children = $('#websites2_child').children();
for(var i=0;i<children.length;i++) {
var label = children[i].getElementsByTagName('span')[0].innerHTML;
if(label === name) {
children[i].click()
}
}
};
And then use it like this:
jQueryImageDD_selectByName('Italiano'); // will select Italiano :)
He does say
You can set almost all properties via object
So, just guessing from the documentation examples he provides on that page... I would think adapting this:
var oHandler = $('#comboboxid').msDropDown().data("dd");
oHandler.size([true|false]);
//Set or get the size property
To the .value property might work. So for you to set the language to Italian, try
var oHandler = $('#comboboxid').msDropDown().data("dd");
oHandler.value('italian');
// Or maybe the way to do it is this:
oHandler.set('value', 'italian');
// Or maybe 'value' shouldn't be in single quotes
//set property
If that doesn't work, you could try looping over all the properties, getting and comparing the value at each index and, when you find it, setting the selected index to that property name.
var languageSelect = $('websites1');
var oHandler = $('#websites1').msDropDown().data("dd");
for(var index = 0; index < languageSelect.length; index++) {
var option = oHandler.item([index]);
if(option == 'italian') {
oHandler.set("selectedIndex", index);
break;
}
}
One of those should work. If not, you're pretty much just going to have to wait for a reply from the author.
You can either use selectedIndex to change the index of the selected option (0 being the first)
document.getElementById("websites1").selectedIndex = 1; //espanol
, or you can use value to change the text of the value (and if there's a match, it will change it automatically).
document.getElementById("websites1").value = 'espanol';
use selectedIndex. See this page. A select control has an options property, which basically is an array of option elements. The first element in your select is options[0], english, so:
document.getElementById("websites1").selectedIndex = 0; //=> english
You can also make the first option selected by default using:
document.getElementById("websites1").options[0]
.defaultSelected = true; //=> english by default
working option (1. destroy msdropdown, 2. select by value, 3. set up msdropdown)
put this code somewhere in js:
jQuery.fn.extend({
setValue: function(value) {
var dd = $(this).msDropdown().data("dd");
dd.destroy();
$(this).val(value);
$(this).msDropdown();
}
});
setting value:
$('#selectorOfmsDropDown').setValue('opt10');
or just:
$("#selector").msDropdown().data("dd").setIndexByValue(newvalue);

Categories