use variables in "document.Form1.checkbox.checked == true" - javascript

in
document.Form1.checkbox.checked == true
can i substitute Form1 and checkbox by javascript variables??
var a= checkbox;
var b= Form1;
document.b.a.checked == true

You can do it like this:
var form = 'Form1';
var field = 'checkbox';
document[form][field].checked == true
Also you can give ID for that checkbox and then use it.
document.getElementById('checkbox1').checked == true

Related

Check value of both text boxes if they have values in it or not

My page have multiple textboxes i wanted to make sure if user select value from text box 1 and leaves text box 2 empty then it should alert a popup that you must have to enter values in both textboxes.
i do not want to compare values with each other.(Like both textbox value must be same)
Textbox 1 is Number field and text box 2 is date field.
If any one value is entered then it should not allow user to submit page it should stop processing and redirect to that textbox which is empty.
Now what i have tried so far.
$( "#button_id" ).click(function() {
var n = document.getElementById('text1');
var m = document.getElementById('text2');
if(n.value.trim() != "" || n.value == undefined)
{
if (n.value.trim() != "" && m.value.trim() == "")
{
alert("text1 should have some value");
return false;
}
}
if(m.value.trim() != "" || m.value == undefined)
{
if (m.value.trim() != "" && n.value.trim() == "")
{
alert("text2 should have some values");
return false;
}
}
});
As mention below code i just wanted to check if textbox is disable or not if textbox is disable then do not test for validation else do.
Partial Solution :
var _domArray = [$("#textbox1"),$("#textbox2")]
var chk = $x('textbox2').disabled = false;
$( "buttonid" ).click(function() {
_domArray.forEach(function(item){
if(item.val() ==''){
var _getId =item.attr('id');
alert(_getId +" should have some value" );
this.browserEvent.preventDefault();
this.browserEvent.stopImmediatePropagation();
return false;
}
})
});
Use the required attribute on your <input>s, then you can check in JavaScript with document.querySelector('form.insertSelectorHere').matches(':valid').
Use an array to store the DOM element,Loop through it and check to check if it is empty, If so through an alert.
Also assuming you are using input type number & date
var _domArray = [$("#text1"),$("#text2")]
$( "#button_id" ).click(function() {
_domArray.forEach(function(item){
if(item.val() ==''){
var _getId =item.attr('id');
alert(_getId +" should have some value" )
}
})
});
Using jquery since you have tagged this with jquery
jsfiddle

checkbox being checked on false - jquery

$('#checkyes').prop('checked', row['checkb']);
var check = row['checkb'];
alert(check);
$('#checkyes').checkboxradio('refresh');
The alert correctly shows the value inside row['checkb'] to be false, yet the checkbox gets ticked anyway. Am I missing some quotations somewhere or can I not use the row value?
Try
$('#checkyes').prop('checked', (row['checkb'] == 'true') ? true : false);
Or
$('#checkyes').prop('checked', (row['checkb'] == 'true') );
Or
var chk = (row['checkb'] == 'true') ? true : false; //Or var chk = (row['checkb'] == 'true');
$('#checkyes').prop('checked', chk );
Problem
row['checkb'] has value string true or false not Boolean value .
So $('#checkyes').prop('checked', row['checkb']); will evaluate to checked.
String value here prop('checked', String) makes it true for all cases .
From Tushar Gupta's answer, I'd suggest:
$('#checkyes').prop('checked', row['checkb'] == 'true');
var isResult = (row['checkb'] == 0) ? false : true;
$('#checkyes').prop('checked', isResult);
$('#checkyes').prop('checked', JSON.parse(row['checkb']));

jQuery - Field values and comparisons

I am making a form validation and want to check a number of radio button values. By default no values are selected. There are two options for each question - yes and no.
First I hide the 'caution message' and check whenever one of the inputs are changed. What I want to happen is when all options are set to no (value is N), then the error message will show, otherwise it will hide. I want it so that if any of the options are then changed to yes the error message will hide. What happens here is if any of the values are changed to yes the error message shows. Maybe I'm over complicating how this should work?
$('.cautionMessage').hide();
$('.weeeDetailsChange input').change(function () {
var ownBrand = $('input[name="ownbrand"]:checked').val();
var resell = $('input[name="resell"]:checked').val();
var ImportBasis = $('input[name="importbasis"]:checked').val();
var distributeEEE = $('input[name="distributeeee"]:checked').val();
var exportEU = $('input[name="exporteu"]:checked').val();
var distanceSelling = $('input[name="distanceselling"]:checked').val();
if ( ownBrand && resell && ImportBasis && distributeEEE && exportEU && distanceSelling === 'Y' ) {
$('.cautionMessage').show();
console.log('Show');
} else {
$('.cautionMessage').hide();
console.log('Hide');
}
});
Ah I see what's happening -- probably just needed a fresh set of eyes on this.
What you're currently doing is checking that only distanceSelling is yes whereas you should be checking that all values are no and running your show/hide based on that since you want to show the message if any of the values are 'yes'.
Try the following:
$('.cautionMessage').hide();
$('.weeeDetailsChange input').change(function () {
var ownBrand = $('input[name="ownbrand"]:checked').val();
var resell = $('input[name="resell"]:checked').val();
var ImportBasis = $('input[name="importbasis"]:checked').val();
var distributeEEE = $('input[name="distributeeee"]:checked').val();
var exportEU = $('input[name="exporteu"]:checked').val();
var distanceSelling = $('input[name="distanceselling"]:checked').val();
if (ownBrand == 'N' && resell == 'N' && ImportBasis == 'N' && distributeEEE == 'N' && exportEU == 'N' && distanceSelling == 'N' ) {
// all values are 'N'
$('.cautionMessage').show();
console.log('Show');
} else {
// not all values are 'N'
$('.cautionMessage').hide();
console.log('Hide');
}
});
I hope I understood that correctly. Hope that helps!
A couple of changes that I made. I use the property checked prop('checked') instead of val() because it actually returns me a Boolean so I do not need to compare it to y or anything. I then flip the hide and show where the caution message is only hidden when all check boxes are check. Click here to see example
$('.caution').hide();
$(".weeeDetailsChange").change(function(){
var ownBrand = $('input[name="ownbrand"]:checked').prop('checked')
var resell =$('input[name="resell"]:checked').prop('checked')
var ImportBasis = $('input[name="importbasis"]:checked').prop('checked')
var distributeEEE = $('input[name="distributeeee"]:checked').prop('checked')
var exportEU = $('input[name="exporteu"]:checked').prop('checked')
var distanceSelling = $('input[name="distanceselling"]:checked').prop('checked')
if ( ownBrand && resell && ImportBasis && distributeEEE && exportEU && distanceSelling) {
$('.caution').hide();
console.log('hide');
} else {
$('.caution').show();
console.log('show');
}
});

Validate radio button that depends on a value in database

views.py
def method(request):
settings = Setting.objects.get(user = user)
return render(request,'index.html',{'settings':settings})
models.py
class Settings(models.Model):
date_format = models.BooleanField(default=False)
index.html:
<script>
function(){
var format1 = document.getElementById("id_date_format_1");
var format2 = document.getElementById("id_date_format_2");
if (settings.date_format == True)
{
$('format1' = checked)
}else{
$('format0' = checked)
}
}
</script>
I want to validate the radio button. I am uisng django.
So if the value in date_format is 1, I need to show the radio button as checked otherwise unchecked.
I tried with the above code but it does not work.
so; django template tag render "{{ settings.date_format }}" --> True or False ok ? date_format variable replace boolean javascript.
var format0 = document.getElementById("id_date_format_0");
var format1 = document.getElementById("id_date_format_1");
var date_format = "{{ settings.date_format }}" == "True" ? true : false;
if (date_format) {
format0.checked = true;
} else {
format1.checked = true;
}
see: http://jsfiddle.net/QsWdx/1/
Use:- $('#format1').attr( "checked", "checked" ) to check the radio button
<script>
function(){
var format1 = document.getElementById("id_date_format_1");
var format2 = document.getElementById("id_date_format_2");
if (settings.date_format == True)
{
$('#format1').attr( "checked", "checked" )
}else{
$('#format0').attr( "checked", "checked" )
}
}
</script>

How do I prevent JavaScript error message from hiding after just first of multiple corrections?

I have a form that validates user input. When the user clicks the submit button and one or more required fields are empty, a "Required" message appears to the right of the field or label and a general message at the top and bottom. This seems to work fine. However, when I test the form by updating one of the empty required fields, the general messages vanish even though other required fields remain blank. How can I prevent this? I appreciate any assistance. Thanks--DJH
$(document).ready(function() {
$('form').submit(function(event){
var isErrorFree = true;
$('input.required, select.required, textarea.required',this).each(function(){
if ( validateElement.isValid(this) == false ){
isErrorFree = false;
};
});
return isErrorFree;
return getFocus;
}); // close .submit()
var validateElement = {
isValid:function(element){
var isValid = true;
var $element = $(element);
var id = $element.attr('id');
var name = $element.attr('name');
var value = $element.val();
var hideMsg = true;
// <input> uses type attribute as written in tag
// <textarea> has intrinsic type of 'textarea'
// <select> has intrinsic type of 'select-one' or 'select-multiple'
var type = $element[0].type.toLowerCase();
switch(type){
case 'text':
case 'textarea':
case 'password':
if ( value.length == 0 ||
value.replace(/\s/g,'').length == 0 ){ isValid = false; hideMsg = false; }
break;
case 'select-one':
case 'select-multiple':
if( !value ){ isValid = false; hideMsg = false; }
break;
case 'checkbox':
case 'radio':
if( $('input[name="' + name +
'"]:checked').length == 0 ){ isValid = false; hideMsg = false; };
break;
} // close switch()
var method = isValid ? 'removeClass' : 'addClass';
var msgStat = hideMsg ? 'removeClass' : 'addClass';
if ( type == 'checkbox' || type == 'radio' ) {
// if radio button or checkbox, find all inputs with the same name
$('input[name="' + name + '"]').each(function(){
// update each input elements <label> tag, (this==<input>)
$('#errorMessage_' + name)[method]('showErrorMessage');
$('#errorMessage1')[msgStat]('showErrorMessage');
$('#errorMessage2')[msgStat]('showErrorMessage');
});
} else {
// all other elements just update one <label>
$('#errorMessage_' + name)[method]('showErrorMessage');
$('#errorMessage1')[msgStat]('showErrorMessage');
$('#errorMessage2')[msgStat]('showErrorMessage');
}
// $('#errorMessage1')[msgStat]('showErrorMessage');
// $('#errorMessage2')[msgStat]('showErrorMessage');
// after initial validation, allow elements to re-validate on change
$element
.unbind('change.isValid')
.bind('change.isValid',function(){ validateElement.isValid(this); });
return isValid;
// close validateElement.isValid()
// close validateElement object
// close ready object
Do you need to specifically write your own validation script?
Seems a lot of what you're testing for is covered in the jQuery validation plugin - http://docs.jquery.com/Plugins/Validation
Might make life easier

Categories

Resources