Issue while evaluating the condition in javascript - javascript

I am fetching one value from controller to jsp and trying to validate the value as follows,
<c:set var="healthWorkerOptions" value='${map["healthWorkerOptions"]}' />
<script>
validateSelectedOption();
function validateSelectedOption()
{
alert("test");
if(healthWorkerOptions != null)
{
alert("not null");
}
else{
alert("null");
}
}
</script>
Value is coming from the controller and able see the fetched value with following statement,
<p> ${healthWorkerOptions} </p>
But while evaluating the condition nothing is happening. What's wrong in my code? I am able to see only test alert but not not null or null alert.
Any suggestion

healthWorkerOptions is not defined in scope of your JS. A debugger should tell you this.
function validateSelectedOption() {
var healthWorkerOptions = '<c:out value="${healthWorkerOptions}" />';
[...]
}

You can directly use el in JavaScript also like below :
healthWorkerOptions = "${healthWorkerOptions}";
if(healthWorkerOptions != null)
{
alert("not null");
} else {
alert("null");
}

Related

How to return a light box error message from a function

I've created a basic form validation script that I want to return an error messages as a light box, rather than using an alert() message. I like the look of featherlight.js, but I can't figure out how to return it from a function? Any other suggestions would be greatly appropriated. Thanks in advance.
The featherlight.js repo
function validate() {
var name = document.forms['userForm']['fname'].value;
if (name == null || name == '') {
alert('Please enter your first name');
return false;
}
}
<label for="first-name">First Name: </label><br>
<input name="fname" type="text" /><br>
<button onclick="validate()">Submit Form</button>
I know this is a bit late, but I think I know what you're after. I've just done a similar thing myself, so I'll put it here incase it helps anyone.
I created a function so you can re-use it elsewhere along with an OK button to close the light box.
function customAlert(message = '') {
var alertBox = $(document.createElement('div'));
alertBox.html('<h3>'+message+'</h3><p><a class="featherlight-close">OK</a></p>');
$.featherlight(alertBox);
}
function validate() {
var name = document.forms['userForm']['fname'].value;
if (name == null || name == '') {
customAlert('Please enter your first name');
return false;
}
}
Basically, you cannot "return" it. What you can do is you can trigger a lightbox event when your conditions are match, like this:
function validate() {
var name = document.forms['userForm']['fname'].value;
if (name == null || name == '') {
$.featherlight($content, $configuration); // Lightbox for wrong validation
return false;
} else {
$.featherlight($content, $configuration); // Lightbox for successful validation
return true;
}
}
And of course, you will need to modify $content and $configuration variables as you want as explained here:
https://github.com/noelboss/featherlight/

How to check if checkbox is checked in asp.net view using Jquery?

I am trying to find out whenever a checkbox on my page is checked and unchecked. I console log to find out the status, but I am always getting an "unchecked" result. What am I doing wrong?
...
<input type="checkbox" id="checkbox_addAuthor" name="checkbox_addAuthor" />
</div>
</form>
#section Scripts
{
<script type="text/javascript">
var checkbox = $('#checkbox_addAuthor');
var authorList = $('#AuthorList');
checkbox.on('click',function(){
if(checkbox.Checked == true)
{
console.log("I am checked")
}
else {
console.log("I am not checked");
}
})
</script>
}
When I run this, the console always prints out "I am not checked". Cant figure out why.
you can use the prop
if($('#checkbox_addAuthor').prop('checked'))
{
// something when checked
}
else {
// something else when not
}
$('#checkbox_addAuthor :checkbox:checked').length > 0;
Use $('#checkbox_addAuthor').val() == "on" to check the state of the checkbox

Having difficulty getting Javascript form to validate

Been looking for an answer for hours now and I still haven't come up with a solution. I've tried looking for similar question, but none have helped, really.
So basically, what doesn't work is that the form submits without any error messages even if there are mistakes on the form. Basically, I could leave the name field empty and the form will still submit once I press the button. Hope this made sense. Any help is appreciated
Code:
function validateFinale()
{
var emailOne = document.getElementById("em1").value;
var emailTwo = document.getElementById("em2").value;
var name = document.getElementById("name1").value;
if (compare())
{
if (name, 'Please enter name'))
{
if (validEmail(getElementById('em1'), 'Email invalid'))
{
}
}
}
return false;
}
function validName(elem, helpmsg) {
if (elem.value.length == 0) {
alert(helpmsg);
return false;
} else {
return true;
}
}
function validEmail(elem, msg) {
var wrongem = /^[\w\-\.\+]+\#[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]+$/;
if (elem.value.match(wrongem)) {
return true;
} else {
alert(msg);
return false;
}
}
function compare() {
if (emailOne != emailTwo) {
alert("Emails not the same");
submitOk = "false";
Document.getElementById("em1").value = " ";
Document.getElementById("em2").value = " ";
Document.getElementById("em1").focus();
} else {
alert("form complete, thank you");
}
}
http://jsfiddle.net/aj240/qgmt5yr8/
you made syntax mistake, first you declare emailOne as local variable, than try reach it in global scope. You should declare variables emailOne and emailTwo in global scope.
var emailOne;
var emailTwo;
function validateFinale()
{
emailOne = document.getElementById("em1").value;
emailTwo = document.getElementById("em2").value;
var name = document.getElementById("name1").value;
One gold tip, try press F12 in your browser and all errors messages would appear in console.
Try setting required ="true" in the input elems:
<input type="text" required ="true"...
Also, if you set type="email" in the e-mail field it will ask for an e-mail address (not at all, though, it just will accept anything with an "#")
And the code validName(getElementById('name1'), ...) should be validName(getElementById('name1').value, ...), or else you'll get all the HTML element

JS - if hidden field's value is "x," then execute function

I think this is pretty simple, but I am writing 1 JavaScript include that will go on multiple pages with a form. All of the pages have a hidden field like this:
<input type="hidden" name="test" value="test1">
Some pages have the value as "test1," while others have "test2." I only want to execute this script for pages with the "test1" value. I do NOT want it on pages with "test2" value.
For reference, here is the JS:
function CheckDay(obj) {
if (obj.value == "F") {
document.getElementsByName("price")[0].value = "29.99";
} else {
document.getElementsByName("price")[0].value = "39.99";
}
}
I'm just not sure how to say, only run if "test" value is "test1". Can anyone help?
You can add condition in the funnction to execute the javascript only when the value of test is test1 (Or you can call the function CheckDay from another function after checking the value)
function CheckDay(obj) {
if(document.getElementsByName('test')[0].value==='test1'){
if (obj.value == "F") {
document.getElementsByName("price")[0].value = "29.99";
} else {
document.getElementsByName("price")[0].value = "39.99";
}
}
}

[JavaScript]: How to define a variable as object type?

I am using following code to check whether a check box on my website page is checked or not. But there are several check boxes and I want to use this same function. I want to call this function from a Submit button click and pass the check box name as argument. It should than validate that check box.
function CheckTermsAcceptance()
{
try
{
if (!document.getElementById('chkStudent').checked)
alert("You need to accept the terms by checking the box.")
return false;
}
catch(err)
{
alert(err.description);
}
}
Just pass a parameter to CheckTermsAcceptance(). You also missed a brace after the alert -- there are two statements in that if block, and you'll always execute the return false without it.
function CheckTermsAcceptance(checkboxName)
{
try
{
if (!document.getElementById(checkboxName).checked) {
alert("You need to accept the terms by checking the box.")
return false;
}
}
catch(err)
{
alert(err.description);
}
}
To call this from your submit button, have a function like validateForm that's called on submit. Then simply construct a list of the checkboxes and pass in their IDs to CheckTermsAcceptance.
Note that this sort of validation is handled very smoothly by jQuery and its ilk. For example, here's the jQuery validation plugin.
function CheckTermsAcceptance(element){
try{
if (!element.checked){
alert("You need to accept the terms by checking the box.")
return false;
}
}catch(err){
alert(err.description);
}
}
and you call it like:
CheckTermsAcceptance(document.getElementById('chkStudent'));
is that it?
Sorry for not answering your questions. But you should seriously consider using jQuery and jQuery validate.
You could also use more arguments to allow for different options as well.
function CheckTermsAcceptance()
{
var ctrl = arguments[0];
var valueExpected = arguments[1];
var outputMessage = arguments[2];
if(valueExpected == null) valueExpected = true;
if(outputMessage == null) outputMessage = "You need to accept the terms by checking the box.";
try
{
if(ctrl.checked == valueExpected)
{
Log.Message(outputMessage);
}
}
catch(err)
{
alert(err.description);
}
}
this function will work with a bit of fix up, pass argument and make sure you do both the alert and the return false in the if statement
function CheckTermsAcceptance(checkBox) //added argument
{
try
{
if (!checkBox.checked) { //added block to group alert and fail case
alert("You need to accept the terms by checking the box.")
return false;
}
return true; //added success case
}
catch(err)
{
alert(err.description);
}
}
once you have this in place you can then use it on your form validation like so
<form id="formid" action="" onsubmit="return validate('formid');">
<input type=checkbox name="name" id="name"><label for="name">Name</label>
<input type=checkbox name="name2" id="name2"><label for="name2">Name2</label>
<input type=submit>
</form>
<script>
function validate(formid) {
var form = document.getElementById(formid);
for (var i = 0; i < form.elements.length; i++) {
var elem = form.elements[i];
if (elem.type == 'checkbox' && !CheckTermsAcceptance(elem)) {
return false;
}
}
return true;
}
</script>
i can confirm that this works in firefox 3.5
also jQuery and jQuery.validate make this very easy to implement in a very declarative way.

Categories

Resources