Execute custom function onChange - javascript

Pure JavaScript.
I have a checkbox in HTML page. I want to execute
App.setCheckedProperty(name, val);
Where name is name attribute of the checkbox and val true/false means checked.
How to implement it? I can't find any materials aboit it on the Net.
UPD:
<input type="checkbox" name="smth" onChange="<WHAT TO DO HERE?>" checked />
Final execution must be equal:
App.setCheckedProperty("smth", false);
UPD2:
Are there any contructions like this.name or this.checked in JavaScript?

you shouldnt do it "inline" inside your html. its just bad practice. i think what you want to do is to loop over a couple of checkboxes?
see this code:
// declare all vars that you need and find all input-elements
var i, input, inputs = document.getElementsByTagName('input');
// loop over all input-elements
for(i = 0; i <= inputs.length; i++) {
input = inputs[i];
// if the current element is a checkbox
if(input.type === 'checkbox') {
//append a click-handler to that checkbox
input.onclick = function () {
// if the checkbox is clicked, you can find the name and the checked-property
App.setCheckedProperty(this.name, this.checked);
};
}
}
and a working example here (i just alert instead of App.setCheckedProperty): http://jsfiddle.net/5wExJ/

Related

JavaScript undo onclick action?

I have an HTML checkbox. It uses an onclick javascript event to increment an integer var by 1.
I want to decrement the var by one if the checkbox is then unchecked. How can I do this?
$('.checkbox').click (function(){
var thisCheck = $(this);
if ( thischeck.is(':checked') ) {
// Do increment
}
else { // DO decrement }
});
just use a conditional statement to check whether the checkbox has been unchecked inside the function where you check whether the function has been checked and increment the value.
$("#inputid input:checkbox").change(function() {
var ischecked= $(this).is(':checked');
if(!ischecked)
var val = val-1;
});

Disable submit button until one in a group of dynamically-created radio buttons selected

I would like to disable a submit button until one of a group of radio buttons is selected. I know there are similar questions out there, but none pertain to a dynamically-created group of radio buttons...
Here is what I have.. a script at the top of the page generates a number of buttons given a user upload in a previous view:
var jScriptArray = new Array(#ViewBag.ColNames.Length);
var array = #Html.Raw(Json.Encode(ViewBag.ColNames));
for( var i = 0; i < #ViewBag.ColNames.Length; i++ ) {
jScriptArray[i] = array[i];
}
var length = #(ViewBag.NCols);
$(document).ready(function () {
for (var i = 0; i < length; i++) {
$('#radioGroupBy').append('<input id="grp' + i +'" type="radio" name="group" value="'+i+'">'+jScriptArray[i]+'</input>')
$('#radioGroupBy').append('<p style="padding:0px;margin:0px;"></br></p>');
}
});
This works, and selecting any of the buttons returns the proper value; great. However, I want to disable the submit button until one of these radio buttons is selected. Using an answer I found on SO earlier, I created the following (this works, but only if I hard code the group of buttons. The issue is it won't work with the Javascript-created group):
var $radioButtons = $("input[name='group']");
$radioButtons.change(function () {
var anyRadioButtonHasValue = false;
// iterate through all radio buttons
$radioButtons.each(function () {
if (this.checked) {
// indicate we found a radio button which has a value
anyRadioButtonHasValue = true;
// break out of each loop
return false;
}
});
// check if we found any radio button which has a value
if (anyRadioButtonHasValue) {
// enable submit button.
$("input[name='submitbtn']").removeAttr("disabled");
}
});
Also, for the sake of thoroughness, here is the submit button:
<input id="submitbtn" name="submitbtn" type="submit" value="Drill Down" disabled="disabled" />
Thanks so much!
Event delegation (also, use .prop() when removing the disabled property to the submit button)
$("#radioGroupBy").on("change", ":radio[name=group]", function() {
var $radioButtons = $(":radio[name=group]");
var anyRadioButtonHasValue = false;
// iterate through all radio buttons
$radioButtons.each(function () {
if (this.checked) {
// indicate we found a radio button which has a value
anyRadioButtonHasValue = true;
// break out of each loop
return false;
}
});
// check if we found any radio button which has a value
if (anyRadioButtonHasValue) {
$("input[name='submitbtn']").prop("disabled", false);
}
});
I figured it out. As Benjamin suggested in comments above, the latter script was executing before the DOM was ready. I solved it by just surrounding the whole script in $(window).load... :
$(window).load(function () {
var $radioButtons = $("input[name='group']");
$radioButtons.change(function () {
var anyRadioButtonHasValue = false;
// iterate through all radio buttons
$radioButtons.each(function () {
if (this.checked) {
// indicate we found a radio button which has a value
anyRadioButtonHasValue = true;
// break out of each loop
return false;
}
});
// check if we found any radio button which has a value
if (anyRadioButtonHasValue) {
// enable submit button.
$("input[name='submitbtn']").removeAttr("disabled");
}
});
});

Javascript to jQuery Get value of Radio button

After having successfully completed an application in Javascript, I am trying to make it more jQuery friendly. However, when I try to get the value of a radio button like so:
// relavent declarations:
var radio = $("[name='buttons']"); // 4 radio buttons
var val = '';
var score = 0;
for( var q in radio ) {
if (radio[q].checked)
val = radio[q].val();
}
if(val === correct) {
score++;
}
What I'm trying to do is make it so that the equivalent in straight Javascript is like this:
for( var q in radio ) {
if (radio[q].checked)
val = radio[q].value;
}
if(val === correct) {
score++;
}
My Javascript console keeps giving me the error "Uncaught TypeError: Object # has no method 'val'" What is the problem?
try this
$('input:radio').each(function(){
if($(this).is(':checked'))
var value = $(this).val();
});
radio[q] will give you a raw DOM node object, you probably want the associated jQuery object, so try radio[q].eq(q).
See: http://api.jquery.com/eq/
Try below code :
$(":radio:checked").each(function(){
val = $(this).val();
})
i think you are writing some thing that have an answer and user if checked correct one then he will get a score
Suggestion 1) Give all the check box the same name , so that only one can be checked
<input type="radio" name="Answer" />
Suggestion 2) get the selected checkbox value from myForm
$('input[name=radioName]:checked', '#myForm').val()
As close as I think you want.
$(document).ready(function() {
var radio = $("input[type='radio']");
for (var i in radio) {
i = parseInt(i);
var r = radio[i];
if ($(r).prop("checked") == true) {
console.log($(r).val());
}
}
})
})
Added the readout of the value

Onsubmit validate change background requried fields?

Anyone know of a good tutorial/method of using Javascript to, onSubmit, change the background color of all empty fields with class="required" ?
Something like this should do the trick, but it's difficult to know exactly what you're looking for without you posting more details:
document.getElementById("myForm").onsubmit = function() {
var fields = this.getElementsByClassName("required"),
sendForm = true;
for(var i = 0; i < fields.length; i++) {
if(!fields[i].value) {
fields[i].style.backgroundColor = "#ff0000";
sendForm = false;
}
else {
//Else block added due to comments about returning colour to normal
fields[i].style.backgroundColor = "#fff";
}
}
if(!sendForm) {
return false;
}
}
This attaches a listener to the onsubmit event of the form with id "myForm". It then gets all elements within that form with a class of "required" (note that getElementsByClassName is not supported in older versions of IE, so you may want to look into alternatives there), loops through that collection, checks the value of each, and changes the background colour if it finds any empty ones. If there are any empty ones, it prevents the form from being submitted.
Here's a working example.
Perhaps something like this:
$(document).ready(function () {
$('form').submit(function () {
$('input, textarea, select', this).foreach(function () {
if ($(this).val() == '') {
$(this).addClass('required');
}
});
});
});
I quickly became a fan of jQuery. The documentation is amazing.
http://docs.jquery.com/Downloading_jQuery
if You decide to give the library a try, then here is your code:
//on DOM ready event
$(document).ready(
// register a 'submit' event for your form
$("#formId").submit(function(event){
// clear the required fields if this is the second time the user is submitting the form
$('.required', this).removeClass("required");
// snag every field of type 'input'.
// filter them, keeping inputs with a '' value
// add the class 'required' to the blank inputs.
$('input', this).filter( function( index ){
var keepMe = false;
if(this.val() == ''){
keepMe = true;
}
return keepMe;
}).addClass("required");
if($(".required", this).length > 0){
event.preventDefault();
}
});
);

How to loop through a radio buttons group without a form?

How do I loop through a radio buttons group without a form in JavaScript or jQuery?
What about something like this? (using jQuery):
$('input:radio').each(function() {
if($(this).is(':checked')) {
// You have a checked radio button here...
}
else {
// Or an unchecked one here...
}
});
You can also loop through all the checked radio buttons like this, if you prefer:
$('input:radio:checked').each(function() {
// Iterate through all checked radio buttons
});
...in case someone wants to do this without jQuery (since it was part of the question):
I'm not sure what you mean by without a form. If you mean you don't want to pass the form element to a javascript function, you could do it like this:
for (var i = 0; i < document.form_name.radio_name.length; i++) {
if (document.form_name.radio_name[i].checked) {
// ...
}
}
If you mean without a form as in you have no form node, you could wrap them in a span (or a div) and use code like this:
var span = document.getElementById("span_id");
var inputs = span.getElementsByTagName("input");
for (var i = 0; i < inputs.length; ++i) {
if (inputs[i].checked) {
// ...
}
}
I can't be too sure what you mean but if you want to do something to all radio buttons on a page you can do this:
$("input:radio").each(function(){
//do something here
});

Categories