Javascript catch unselected radio button along with textboxes and alert - javascript

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.

Related

Javascript disabled button if checkboxes are not choosen - problem

I wrote a code, that make the button not disabled when you check at least one checkbox with class "sum".
I want to change the code, so I have to classes for and you can check only one checkbox (or two of them) to make the button not disabled.
This is what I have and it works with only one class:
var checkBoxes = $('.sum');
checkBoxes.change(function () {
$('#dashboardbuttonpay').prop('disabled', checkBoxes.filter(':checked').length < 1);
});
$('.sum').change();
});
This is what I tried to do, but OR op does not work:
var checkBoxes = $('.sum' || **'.checkAll'**);
checkBoxes.change(function () {
$('#dashboardbuttonpay').prop('disabled', checkBoxes.filter(':checked').length < 1);
});
$('.sum' || **'.checkAll'**).change();
});
The code works with && operator, but I do not need this.
Using the OR operation on strings this way does not make sense. If you do this with two non-empty strings, you always get the first operand:
console.log('a' || 'b')
In order to select multiple elements, you just separate them by comma:
var checkBoxes = $('.sum, .checkAll');
The code works with && operator, but I do not need this.
Not really. 'a' && 'b' always returns 'b'.
You could check for the amount of checked inputs then add/remove the disabled property in the change event handler.
var checkBoxes = $('.sum','.checkAll');
checkBoxes.change(function () {
if (checkBoxes.filter(':checked').length > 0) {
$('#dashboardbuttonpay').prop('disabled', null);
} else {
$('#dashboardbuttonpay').prop('disabled');
}
});
This way you capture if one or more checkboxes are checked before remove the disabled attribute of the button. Which lets you enable the button with either one or both checkboxes selected.
var checkBoxes = $('.sum','.checkAll');
checkBoxes.change(function () {
if(checkBoxes.filter(':checked').length > 1)
$('#dashboardbuttonpay').prop('disabled',true);
else
$('#dashboardbuttonpay').prop('disabled',false);
});

[javascript]radio button jumps to first option

I have a standard html from with a couple of radio buttons (3 of them actually).
With:
function abo_show()
{
var x = document.gms_option.gms_element1;
console.log(x.value);
if (x.value = "1") {
document.getElementById("abo").style.display="block";
document.getElementById("gms_abo1").style.display="table-row";
document.getElementById("gms_abo2").style.display="table-row";
document.getElementById("gms_abo3").style.display="table-row";
}
else {
document.getElementById("abo").style.display="block";
document.getElementById("gms_abo1").style.display="table-row";
document.getElementById("gms_abo2").style.display="none";
document.getElementById("gms_abo3").style.display="none";
}
}
I try to show a couple of extra buttons, based on the first 3. The new ones are in a div "abo", that is hidden by default (in css: "display:none").
But when I click on a radio button to select, it executes and jumps to option 1.
No idea why. Could someone explain and help?
x.value = "1" because of this.
you use a single = doing an assignment not a comparison. This causes the if to always succeed. just use == or even ===instead.
You have an easy = in an if statement. Its not compared, it is set.
Your code sets x.value to "1" instead of comparing it.
Use:
if(x.value=="1") {

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();
}

Clear a form and populate jquery

I am trying to clear a form and then repopulate it with new data. I have a page that has a list of search histories, along with a "search again" button, when clicked, it takes that search history string, split it, then match those again all the various form items; checkbox, radio, etc. The form has basically every kind of form element in it and everything is populating like I want it to except the checkboxes. The first time I click the populate form button, it works fine, but after the first click all the checkboxes start going haywire...some items populating like they should, some not, in a strange random pattern. I have not included the html because I don't think it is necessary but if anyone needs more info, please let me know.
This resets the form. I have tested this independently and it works.
function form_reset(){
$('#hosp_search_form')[0].reset();
$('#hosp_search_form').find("input[type=text], textarea").val("");
$('input[type=checkbox]').each(function(){
$('input[type=checkbox]').removeAttr('checked');
});
$('input[type=number]').val('');
$('input[type=radio]').each(function(){
$(this).removeAttr('checked');
});
On click, first clear the form of previous values, then grab the other needed values and format them...this part gets a little ugly in sections but I have consoled out all the values and everything is how it should be.
$('.search_again_btn').on('click', function(){
form_reset();
$('#hosp_search_form').find('input[type=checkbox]').removeAttr('checked');
var id = $(this).data('id');
var searchstring = $('#searchstring_' + id).text();
var patientcode = $('#patientcode_' + id).text();
var mrn = $('#mrn_' + id).text();
var first_name = patientcode.substr(0,2);
var last_name = patientcode.substr(2,2);
var age = patientcode.substr(4,3);
var gender = patientcode.substr(6,2);
var age = age.replace(/\D+/g, '');
gender = gender.replace(/[0-9]/g, '');
Populates some of the form, works fine
//populate fields in search form
$('input[name=fn]').val(first_name);
$('input[name=ln]').val(last_name);
$('input[name=patientage]').val(age);
$('input[name=mrn]').val(mrn);
Populate another part of the form, also always works as needed
//populate gender fields
if(gender == 'F'){
$('.female').attr('checked', 'checked');
}
if(gender == 'M'){
$('.male').attr('checked', 'checked');
}
Here is where I suspect the issue is. splitsearch is a long string (a previous search history) with items separated by a . and they get split into separate items. I console logged this, it correctly breaking it into the smaller values like I need, then iterate through those and iterate through all the checkboxes which each have a data attr holding values that can be in the splitsearch. If a value matches, it should make it checked. This works every time the first time, for any combo of splitsearch/search string values, but after the first time, I don't know what it is doing. I expect that each click, the form is cleared and it does the value matching again as I described.
//populate checkboxes
var splitsearch = searchstring.split('. ');
$.each(splitsearch, function(key, value){
$('input[type=checkbox').each(function(keyb, checkbox){
item = $(checkbox).data('services');
if(item == value){
$(this).attr('checked', 'checked');
console.log($(this));
}
});
This is doing the same as the above but works every time...probably because there is never multiple combinations like with checkboxes.
$('input[name=payor]').each(function(k, radio){
if(value == $(radio).data('payors')){
$(this).attr('checked', 'checked');
//console.log($(this));
}
});
Also like the above and works.
$('input[name=bedtype]').each(function(keyc, radio){
bed = $(radio).data('bed');
if(bed == value){
$(this).attr('checked', 'checked');
}
});
This part below is quite ugly but is populating the form like I need every time.
//if searchstring contains Needs Transportation, returns true, else returns false
if(value.indexOf("Needs Transportation") > -1 === true){
$('.transyes').attr('checked', 'checked');
}
if(value.indexOf("Near hospital") > -1 != true){
$('input[name=desiredzip]').val(searchstring.substr(5,5));
}
if(value.indexOf("5 mile radius") > -1 === true){
$('.miles_5').attr('checked', 'checked');
}
if(value.indexOf("10 mile radius") > -1 === true){
$('.miles_10').attr('checked', 'checked');
}
if(value.indexOf("15 mile radius") > -1 === true){
$('.miles_15').attr('checked', 'checked');
}
if(value.indexOf("20 mile radius") > -1 === true){
$('.miles_20').attr('checked', 'checked');
}
});
Scrolls the window up to the populated search form and show it.
window.scrollTo(0,100);
$('#search_show').show();
});
Just a thought but, it might help you to restructure your code a bit to keep it DRY.
// used to Hold search data in local or global
var data;
function form_reset() {
// clear form
}
function get_search_data() {
// populate data with search results
}
function form_populate() {
// use data to populate form
}
$('.search_again_btn').on('click', function(){
get_search_data();
form_reset();
form_populate();
});
// Initial Load of form
get_search_data();
form_populate();
that way you use the same population function initially as you do when you refresh and it forces you to put your data into a variable that can be seen in both the clear and populate functions removing your reliance on this and $(this).
also you need to bear in mind that the value of this inside a click function is going to be in the context of the click event itself and not the JavaScript object that the rest of your code belongs to.

how to turn on error messages and turn off depending on what the user inputs using jquery

I am trying to validate a form and I want to be able to toggle the error messages off and on when the user inputs a value into the form field. This is what I have so far that is not working:
$('#uTagNum').blur(function() {
var tagNumber=$(this).val();
if (tagNumber.length < 9){
$('#tagErrorMsg').html('<div>Invalid format.Hover over Tag Number column name to see valid formats</div>');
$('#uTagNum').blur(function() {
$('#tagErrorMsg').hide();
});
});
If the user puts in "Dgfh578" and it is not 9 characters or digits long then I need the tagErrorMsG to appear below the field. If the user deletes what they typed the the error message will disappear unless again they type less then 9 characters or digits.
You have some syntax errors and you probably don't want to use hide(), just clear the HTML for #tagErrorMsg. Have a look at this example - http://jsfiddle.net/jayblanchard/mqeCj/
$('#uTagNum').blur(function () {
var tagNumber = $(this).val();
console.log(tagNumber);
if (tagNumber.length < 9) {
$('#tagErrorMsg').html('<div>Invalid format.Hover over Tag Number column name to see valid formats</div>');
} else {
$('#tagErrorMsg').html('');
}
});

Categories