I wrote this code to switch between radio buttons and show my custom alert.
<script>
function test() {
if (radio[0].checked = true) {
alert("hello1");
}
if (radio[1].checked = true) {
alert("hello2");
}
}
</script>
<input type="radio" onclick="test()" value="0">
<input type="radio" onclick="test()" value="1">
When check any of radio buttons it must show specific alert.
What is wrong?
You should name your radio buttons, and call them from javascript.
<script>
function test() {
if (document.getElementById('radio1').checked == true) {
alert("hello1");
}
if (document.getElementById('radio2').checked == true) {
alert("hello2");
}
}
</script>
<input type="radio" id="radio1" onclick="test()" value="0">
<input type="radio" id="radio2" onclick="test()" value="1">
Two things you need to take note here:
1) You must use the 'name' attribute in the radio button. Otherwise you won't be able to check the radio button.
2) You cannot use radio[0] to point to the radio button. You can assign an ID to it and use getElementById method to use it in Javascript. Another easy way is to pass the object to the function. Please refer to the sample code below:
<script>
function test(radioObj) {
if(radioObj.value == "0")
alert("Hello1");
else if (radioObj.value == "1")
alert("Hello2");
}
</script>
<input type="radio" name="test" onclick="test(this)" value="0">
<input type="radio" name="test" onclick="test(this)" value="1">
radio[0] and radio[1] are defined in your html but not in your javascript. You can try using JQuery or one of the many javascript selector libraries. Or use getElementById
Related
In my application i have two radio buttons,one text box and one button
<input type="radio" name="myRadio" value="red" id="myRadio" checked>Red color
<input type="radio" name="myRadio" value="Blue" id="myRadio">Blue color
<input type="text" id="txtShareCount" name="txtColor"/>
<input type="submit" name="btnsubmit" value="Blue" id="btnsubmit">submit
Here when i check Blue color radio button text box will appear
what i want is, I need to do validation for text box in jquery when i check Blue color radio button if text box is empty then click submit button it display alert message how can i do this in jquery
I did this in javascript it works fine but I need in jquery how can i do this in jquery
To get the value of your radio use:
$('input[name=myRadio]:checked', '#myForm').val()
Or if you're not using a form
$('input[name=myRadio]:checked').val()
For radiobutton you can use :checked selector - $('#myRadio:checked')
As per the traditions and the documentations. Your js gets messed up if you have more than 1 element with same id. So instead of using getElementById() use getElementsByName()
So something like this
function validateRadio() {
var radios = document.getElementsByName("myRadio");
var formValid = false;
var i = 0;
while (!formValid && i < radios.length) {
if (radios[i].checked)
formValid = true;
i++;
}
if (!formValid)
alert("Must check some option!");
return formValid;
}
Note :
1-don't have multiple elements with the same Id
2-when use getElementById , you must enter id attribute
Try this
function myFunction() {
if (document.getElementById('myRadioRed').checked == true || document.getElementById('myRadioBlue').checked == true) {
if (document.getElementById('txtShareCount').value == "") {
alert("Please Enter Color");
document.getElementById("txtShareCount").focus();
return false;
}
return false;
}
else { return true; }
}
<input type="radio" name="myRadio" value="red" id="myRadioRed" checked>Red color
<input type="radio" name="myRadio" value="Blue" id="myRadioBlue">Blue color
<input type="text" id="txtShareCount" name="txtColor" />
<input type="button" name="btnsubmit" value="Blue" id="btnsubmit" onclick="myFunction()"/>
I have been attempting to allow radio buttons to be deselected using jQuery, but I am running into issues with the prop function. When this code runs, my conditional ($(e.currentTarget).prop('checked')) always evaluates to true.
Here is a fiddle which demonstrates my issue: Jsfiddle
FYI: I am using jQuery 1.8.2, and I cannot update it because it is a legacy project with many dependencies. Also, I MUST use radio buttons per the client's request.
Javascript:
$("input[name=optionMedia]").click(function(e) {
if ($(e.currentTarget).prop('checked')) {
$(e.currentTarget).prop('checked', false);
}
});
Html:
<input class="bigSizeInput" type="radio" id="audioVideo" name="optionMedia" value="1"/>
<input class="bigSizeInput" type="radio" id="showReel" name="optionMedia" value="2" />
You can do it like this
$('input.bigSizeInput').mouseup(function() {
if ($(this).is(':checked')) {
setTimeout(function() {
$('input.bigSizeInput:checked').prop('checked', false);
}, 1)
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input class="bigSizeInput" type="radio" id="audioVideo" name="optionMedia" value="1" />
<input class="bigSizeInput" type="radio" id="showReel" name="optionMedia" value="2" />
This is because checked is a property. If its there it is true, if its not it is not true. Hence you either should switch to a checkbox or use
$("..").removeProp('checked')
Using checkbox to check/uncheck is better than radio button. But if you want to use radio button, you need to check if radio is checked, copy it using and remove checked attribute of copied element and then insert it after target radio. At the end remove original radio.
$(document).on("mousedown", "input[name=optionMedia]", function(e) {
if (this.checked)
$(this).clone().prop('checked', false).insertAfter(this).end().remove();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<input class="bigSizeInput" type="radio" id="audioVideo" name="optionMedia" value="1"/>
<input class="bigSizeInput" type="radio" id="showReel" name="optionMedia" value="2" />
I want to make the input field read only on the base of other input field value, for example,
<form action="">
<input type="radio" name="sex" value="male">Male<br>
<input type="radio" name="sex" value="female">Female <br/>
Age: <input type="text" name="age"><br>
</form>
If someone choose Female, then the age input should become read only, means that it should be fade out then no value can be entered. Is this possible, and how?
Have you tried using JQuery? try this
$('input[type=radio][name=sex]').change(function() {
if (this.value == 'female') {
$("#AgeId").prop("readonly",true);
}
else{
$("#AgeId").prop("readonly",false);
}
});
There are several options on this, but basically if you want a fade effect you need a color to go along with it to display a transition. My answer is an implementation of jQuery disable enable click event with fade
JQuery:
$('input[type=radio]').click(function () {
if ($(this).val() == "female") {
// disable input
$('input[name=age]').fadeOut(20, function () {
$(this).prop('disabled', true);
$(this).css('background', '#c0c0c0').fadeIn(1000);
});
} else {
//enable input
$('input[name=age]').prop('disabled', false);
$('input[name=age]').css('background', '#ffffff');
}
});
Here is a demonstration.
EDIT:
After playing with this a little bit more I changed the animation lengths to look more natural.
In simple way,you can do disable in javascript function.
<script language="javascript">
function female_CLK(){
document.getElementById("age").readOnly = true;
document.getElementById("age").style.backgroundColor = "#CCCCCC";
}
</script>
<input type="radio" name="sex" value="male">Male<br>
<input type="radio" name="sex" value="female" onclick="female_CLK()">Female <br/>
Age: <input type="text" name="age" id="age"><br>
I usually work with PHP so sadly don't have some basic JS principles down. This is all I want to accomplish--I've seen many posts on this topic but they are usually beyond what I need.
Here is my form:
<input type="checkbox" name="checkbox" value="check" />
<input type="submit" name="email_submit" value="submit" onclick="----??----" />
The checkbox is a simple "I agree". I want the submit button to be pressed and it will only submit if that check box is selected.
Here's the thing: I want the simple, cheating way -- no methods -- just some inline code in that form (assuming its not overly long?). This is not a public page, I just need something quick and simple with that type of validation. If its unchecked, it will throw an alert(); if its checked it will submit via post through php and go on as normal.
You could use:
if(!this.form.checkbox.checked)
{
alert('You must agree to the terms first.');
return false;
}
(demo page).
<input type="checkbox" name="checkbox" value="check" />
<input type="submit" name="email_submit" value="submit" onclick="if(!this.form.checkbox.checked){alert('You must agree to the terms first.');return false}" />
Returning false from an inline event handler will prevent the default action from taking place (in this case, submitting the form).
! is the Boolean NOT operator.
this is the submit button because it is the element the event handler is attached to.
.form is the form the submit button is in.
.checkbox is the control named "checkbox" in that form.
.checked is true if the checkbox is checked and false if the checkbox is unchecked.
For now no jquery or php needed. Use just "required" HTML5 input attrbute like here
<form>
<p>
<input class="form-control" type="text" name="email" />
<input type="submit" value="ok" class="btn btn-success" name="submit" />
<input type="hidden" name="action" value="0" />
</p>
<p><input type="checkbox" required name="terms">I have read and accept SOMETHING Terms and Conditions</p>
</form>
This will validate and prevent any submit before checkbox is opt in. Language independent solution because its generated by users web browser.
You can do something like this:
<form action="../" onsubmit="return checkCheckBoxes(this);">
<p><input type="CHECKBOX" name="MyCheckbox" value="This..."> This...</p>
<p><input type="SUBMIT" value="Submit!"></p>
</form>
<script type="text/javascript" language="JavaScript">
<!--
function checkCheckBoxes(theForm) {
if (
theForm.MyCheckbox.checked == false)
{
alert ('You didn\'t choose any of the checkboxes!');
return false;
} else {
return true;
}
}
//-->
</script>
http://lab.artlung.com/validate-checkbox/
Although less legible imho, this can be done without a separate function definition like this:
<form action="../" onsubmit="if (this.MyCheckbox.checked == false) { alert ('You didn\'t choose any of the checkboxes!'); return false; } else { return true; }">
<p><input type="CHECKBOX" name="MyCheckbox" value="This..."> This...</p>
<p><input type="SUBMIT" value="Submit!"></p>
</form>
You can do the following:
<form action="/" onsubmit="if(document.getElementById('agree').checked) { return true; } else { alert('please agree'); return false; }">
<input type="checkbox" name="checkbox" value="check" id="agree" />
<input type="submit" name="email_submit" value="submit" />
</form>
Here is a working demo - http://jsfiddle.net/Ccr2x/
If your checkbox has an ID of 'checkbox':
if(document.getElementById('checkbox').checked == true){ // code here }
HTH
var confirm=document.getElementById("confirm").value;
if((confirm.checked==false)
{
alert("plz check the checkbox field");
document.getElementbyId("confirm").focus();
return false;
}
If the check box's ID "Delete" then for the "onclick" event of the submit button the javascript function can be as follows:
html:
<input type="checkbox" name="Delete" value="Delete" id="Delete"></td>
<input type="button" value="Delete" name="delBtn" id="delBtn" onclick="deleteData()">
script:
<script type="text/Javascript">
function deleteData() {
if(!document.getElementById('Delete').checked){
alert('Checkbox not checked');
return false;
}
</script>
Another simple way is to create a function and check if the checkbox(es) are checked or not, and disable a button that way using jQuery.
HTML:
<input type="checkbox" id="myCheckbox" />
<input type="submit" id="myButton" />
JavaScript:
var alterDisabledState = function () {
var isMyCheckboxChecked = $('#myCheckbox').is(':checked');
if (isMyCheckboxChecked) {
$('myButton').removeAttr("disabled");
}
else {
$('myButton').attr("disabled", "disabled");
}
}
Now you have a button that is disabled until they select the checkbox, and now you have a better user experience. I would make sure that you still do the server side validation though.
Another Simple way is to create & invoke the function validate() when the form loads & when submit button is clicked.
By using checked property we check whether the checkbox is selected or not.
cbox[0] has an index 0 which is used to access the first value (i.e Male) with name="gender"
You can do the following:
function validate() {
var cbox = document.forms["myForm"]["gender"];
if (
cbox[0].checked == false &&
cbox[1].checked == false &&
cbox[2].checked == false
) {
alert("Please Select Gender");
return false;
} else {
alert("Successfully Submited");
return true;
}
}
<form onload="return validate()" name="myForm">
<input type="checkbox" name="gender" value="male"> Male
<input type="checkbox" name="gender" value="female"> Female
<input type="checkbox" name="gender" value="other"> Other <br>
<input type="submit" name="submit" value="Submit" onclick="validate()">
</form>
Demo: CodePen
Target it by id and then use this code:
function check(){
if(document.getElementById('yourid').checked
{
return false;
}
else
{
alert ("checkbox not checked");
return false;
}
}
var testCheckbox = document.getElementById("checkbox");
if (!testCheckbox.checked) {
alert("Error Message!!");
}
else {
alert("Success Message!!");
}
Guys you can do this kind of validation very easily. Just you have to track the id or name of the checkboxes. you can do it statically or dynamically.
For statically you can use hard coded id of the checkboxes and for dynamically you can use the name of the field as an array and create a loop.
Please check the below link. You will get my point very easily.
http://expertsdiscussion.com/checkbox-validation-using-javascript-t29.html
Thanks
I want replace a p tag value if a radio is checked.
I write some JS to do this,but nothing changed.
this is my code(I use jquery)
<script>
$(function(){
if ($('#A:checked')) {
$("#change_me").html('<input type="radio" value="1" name="fruit">')
}
if ($('#B:checked')) {
$("#change_me").html('<input type="radio" value="2" name="fruit">')
}
}
</script>
<input type="radio" name="e" id="A" checked="checked">
<input type="radio" name="e" id="B">
<p id="change_me">
<input type="radio" value="1" name="fruit">
</p>
Thanks.
The :checked selector matches elements that are currently checked.
Writing $('#B:checked') returns a jQuery object containing either zero or one element. It cannot be used directly as a condition.
Instead, you can check if ($('#B:checked').length) to see whether the jQuery object has anything in it.
First, you don't need to recreate the radio button if only the value is changing.
$(function(){
if ($('#A:checked').size() > 0) {
$("#change_me input[type=radio]").val('1')
}
if ($('#B:checked').size() > 0) {
$("#change_me input[type=radio]").val('2')
}
}
HTML:
<input type="radio" name="e" id="A" checked="checked">
<input type="radio" name="e" id="B">
<p id="change_me">
<input type="radio" value="1" name="fruit">
</p>
Replace the JavaScript code you have with the following
$(function(){
$('input[name=e]').change(function(){
if($(this).attr('id') == 'A')
{
$("#change_me input").val('1');
}
else
{
$("#change_me input").val('2');
}
});
});