Enabling Disabling Text Fields using PHP when a radio button is clicked - javascript

I have 2 radio buttons(Enable/Disable) and 3 text boxes. I want to disable the 3 textboxes if disable radio button is clicked.
<Input type = 'Radio' Name ='target' value= 'r1'>Enable
<Input type = 'Radio' Name ='target' value= 'r2'>Disable
T1: <input type="text" name="t1">
T2: <input type="text" name="t2">
T3: <input type="text" name="t3">
This change should happen as soon as I select one of the radio button. I am using PHP. TIA!

Although, using jQuery will make it easier, the following is one way to do it purely in JavaScript:
let textboxes = document.querySelectorAll('input[type=text]');
document.querySelectorAll('input[name=target]')
.forEach(function(radio) {
radio.addEventListener('change', function(e) {
let value = e.target.value;
if (value === 'r1') {
textboxes
.forEach(function(textbox) {
textbox.disabled = false;
});
} else if (value === 'r2') {
textboxes
.forEach(function(textbox) {
textbox.disabled = true;
});
}
});
});
<Input type='Radio' Name='target' value='r1'>Enable
<Input type='Radio' Name='target' value='r2'>Disable
<br><br>
T1: <input type="text" name="t1">
T2: <input type="text" name="t2">
T3: <input type="text" name="t3">
It basically listens for the change event of the radio buttons and the loops through the text boxes to enable/disable them.

$('.radio').click(function(e) {
var val = $(this).val();
if(val=="r2") $('input[type="text"]').attr('disabled','disabled');
else $('input[type="text"]').removeAttr('disabled');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label><Input class="radio" type = 'Radio' checked Name ='target' value= 'r1'>Enable </label>
<label><Input class="radio" type = 'Radio' Name ='target' value= 'r2'>Disable </label><br /><br />
T1: <input type="text" name="t1">
T2: <input type="text" name="t2">
T3: <input type="text" name="t3">

As per my comments Here is the code. use jquery code with other text box. make sure you should include jquery library at the top of the code
$(document).ready(function() {
$("#enable").click(function() {
$("#t1").attr("disabled", false);
});
$("#disable").click(function() {
$("#t1").attr("disabled", true);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>JS Bin</title>
</head>
<body>
<Input type = 'Radio' Name ='target' value= 'r1' id="enable">Enable
<Input type = 'Radio' Name ='target' value= 'r2' id="disable">Disable
T1: <input type="text" name="t1" id="t1">
</body>
</html>

Well, as you are using PHP, which is a server-side language, whenever you click radiobutton, refresh the page, and the radiobutton will get back to the unchecked state. So for this, you have to use JavaScript, and jquery is the best way to work with DOM elements. You need to add a few more lines of code. Don't forget to add jQuery in your HTML's ` tag.
<script type="text/javascript">
$(document).ready(function () {
$("#enable").click(function () {
$("#t1").attr("disabled", true);
});
$("#disable").click(function () {
$("#t1").attr("disabled", false);
});
});
</script>

Related

Adding messages to or below input

I have this form that has a series of inputs. Input 1 changes the options for Input 2. Input 2 is blank and until input one is filled, I need to make it so that if the user clicks on input 2 to try to fill out first a message tells them to please select from input 1 first.
I have jQuery doing an alert box currently but how can I have the message show up in the input or right below it?
CodePen: https://codepen.io/anon_guy/pen/WXgZQw
HTML:
<form>
Input-1:<br>
<input type="text" name="first" id="one"><br>
Input-2:<br>
<input type="text" name="second" id="two" >
</form>
jQuery:
$( "#two" ).click(function() {
alert( "Please enter Input 1 First" );
});
It would make more sense, and be a better user experience, to only enable input 2 once input 1 has received a value. You can do that using the input event, like this:
$('#one').on('input', function() {
$('#two').prop('disabled', this.value.trim() == '');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
Input-1:<br>
<input type="text" name="first" id="one"><br>
Input-2:<br>
<input type="text" name="second" id="two" disabled="disabled">
</form>
To add it inside the first input box (as a placeholder):
$("#two").click(function() {
if ($("#one").val() == "") {
$("#one").attr("placeholder", "Please enter Input 1 First");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
Input-1:<br>
<input type="text" name="first" id="one"><br> Input-2:
<br>
<input type="text" name="second" id="two">
</form>
To add it as a message below the inputs:
$("#two").click(function() {
if ($("#one").val() == "") {
var newDiv = document.createElement('div');
newDiv.id = "newDiv";
newDiv.innerText = "Please enter Input 1 First";
$("form").append(newDiv, $("#two").next());
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
Input-1:<br>
<input type="text" name="first" id="one"><br> Input-2:
<br>
<input type="text" name="second" id="two">
</form>
The if statement will cause the message to only display if the first input box has no value:
if ($("#one").val() == "")
You can dynamically insert text/html via after() if the criteria isn't met. Though a more ideal approach would be to use focus over click in this case:
$( '#two' ).on('focus', function() {
if (!$('#one').val().length) {
$('#two').after('<p>Please enter Input 1 First</p>');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
Input-1:<br>
<input type="text" name="first" id="one"><br>
Input-2:<br>
<input type="text" name="second" id="two" >
<p class="warning"></p>
</form>
You need to attach it to the parent.
You can evaluate the first input field to see if it is empty. There are a number of things you can do to remove the appended div.
$( "#two" ).click(function() {
if($("#one").val("")){
$(this).parent().append("<div>Please enter Input 1 First</div>");
}
});

How to validate radio button and text field javascript

Below is my code
<!DOCTYPE html>
<head>
</head>
<body>
<form action="script.php" method="post" id="Form1">
<input name="radioGroup" type="radio" value="Radio1" id="Radio1id">
<input name="radioGroup" type="radio" value="Radio2" id="Radio2id">
<input name="radioGroup" type="radio" value="Radio3" id="Radio3id">
<br>
<br>
<input type="text" size="30" id="name" placeholder="Name*"><br>
<input type="text" size="30" id="email" placeholder="Email*"><br>
<input type="text" size="30" id="comments" placeholder="Comments (Optional)"><br><br>
<input type="submit">
</form>
</body>
</html>
Is there any way to validate radio button and text filed at same time. for an example if radio button is not checked or text field not used. should get a alert window.
Thanks,
Try something like that, or use JQuery because is easy to use for validation
if((document.getElementById('Radio1id').checked) && document.getElementById('name').value != "") {
//Action for checked radio button and text box without value
}else if(document.getElementById('Radio2id').checked) {
//Another Action . . .
}
if((document.getElementById('Radio1id').checked == false) && document.getElementById('name').value != "") {
//Action for NON checked radio button and text box without value
}
by using jQuery.
// valid syntax for jQuery
$("#Radio1id").is(":checked"); // for radio button
$("#email").val()===""; // for any input
use jQuery Validator , gives you more feature and choices down the road with any project. Plus, you can ask questions on GitHub.

put html checkbox value into text field

I have a checkbox with a value of U
i want to put this value into a text input when the checkbox is checked.
how can i do this using javascript or jquery? I need to be able to do it on multiple checkboxes and input text fields too
HTML
<input type="checkbox" value="U" id="checkBox"/>
<input type="text" value="" id="textInput" />
JQUERY
$("#checkBox").change(function(){
$("#textInput").val($(this).val());
});
DEMO
Try this,
HTML
<label><input type="checkbox" value="U" />Check</label>
<input type="text" />
SCRIPT
$('input[type="checkbox"]').on('click',function(){
var is_checked=$(this).prop('checked');
var val='';
if(is_checked)
val=this.value;
$('input[type="text"]').val(val);
});
Working Demo
the simpliest way to do this :o)
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
window.onload = function() {
var checkboxInput = document.getElementById('checkboxInput'),
textInput = document.getElementById('textInput');
checkboxInput.addEventListener('click', UpdateTextInput, false);
};
function UpdateTextInput () {
if(checkboxInput.checked) {
textInput.value = checkboxInput.value;
}
else {
textInput.value = '';
}
}
</script>
</head>
<body>
<input type="checkbox" id="checkboxInput" value="U"/>
<input type="text" id="textInput" />
</body>
</html>
Assuming one textbox is associated with every checkbox like below.
HTML Pattern :
<input type="checkbox" value="test1" id="test1" checked><label>Test</label>
<input type="text" class="text1"id="textbox1" name="textbox1" value="">
jQuery:
$('input[type="checkbox"]').change(function() {
var vals = $(this).val();
if($(this).is(':checked')){
$(this).next().next("input[type='text']").val(vals);
}else{
$(this).next().next("input[type='text']").val("");
}
});
Here is the working demo : http://jsfiddle.net/uH4us/

enabled and disabled text input on checkbox checked and unchecked

i've checkbox and text input
What I need is to enable text input when i check the checkbox and to disable text input when i uncheck the checkbox
I'm using the following code but it do the reverse enable when unchecked / disable when checked so how to adjust it fit with my needs.
<input type="checkbox" id="yourBox">
<input type="text" id="yourText">
<script>
document.getElementById('yourBox').onchange = function() {
document.getElementById('yourText').enabled = this.checked;
};
</script>
any help ~ thanks
You just need to add a ! in front of this.checked.
Here's an example that shows the change:
document.getElementById('yourBox').onchange = function() {
document.getElementById('yourText').disabled = !this.checked;
};
<input type="text" id="yourText" disabled />
<input type="checkbox" id="yourBox" />
A jQuery solution could be this one:
<script>
$('#yourBox').change(function() {
$('yourText').attr('disabled',!this.checked)
});
</script>
It is the same as Minko's answer but I find it more elegant.
Try it. If you use a label then add onmousedown to it
<form >
<input type="text" id="yourText" disabled />
<input type="checkbox" id="yourBox" onmousedown="this.form.yourText.disabled=this.checked"/>
</form>
A better solution could be:
var checkbox = document.querySelector("#yourBox");
var input = document.querySelector("#yourText");
var toogleInput = function(e){
input.disabled = !e.target.checked;
};
toogleInput({target: checkbox});
checkbox.addEventListener("change", toogleInput);
<input type="checkbox" id="yourBox">
<input type="text" id="yourText">
function createInput( chck ) {
if( jQuery(chck).is(':checked') ) {
jQuery('<input>', {
type:"text",
"name":"meta_enter[]",
"class":"meta_enter"
}).appendTo('p.checkable_options');
}
else {
jQuery("input.meta_enter").attr('disabled','disabled');
}
}
createInput( chck );
<input type="radio" name="checkable" class="checkable" value="3" />
<input type="radio" name="checkable" class="checkable" value="4" onclick="createInput(this)" />

make checkbox behave like radio buttons with javascript

I need to manipulate the behavior of the check boxes with javascript. They should basically behave like radio buttons (only one selectable at a time, plus unselect any previous selections).
The problem is that I can't use plain radio buttons in first place, because the name attribute for each radio button would be different.
I know its not the ultimate and shiniest solutions to make an apple look like a pear, and w3c wouldn't give me their thumbs for it, but it would be a better solution right now than to change the core php logic of the entire cms structure ;-)
Any help is much appreciated!
HTML :
<label><input type="checkbox" name="cb1" class="chb" /> CheckBox1</label>
<label><input type="checkbox" name="cb2" class="chb" /> CheckBox2</label>
<label><input type="checkbox" name="cb3" class="chb" /> CheckBox3</label>
<label><input type="checkbox" name="cb4" class="chb" /> CheckBox4</label>
jQuery :
$(".chb").change(function() {
$(".chb").prop('checked', false);
$(this).prop('checked', true);
});
if you want user can unchecked selected item :
$(".chb").change(function() {
$(".chb").not(this).prop('checked', false);
});
Demo :
http://jsfiddle.net/44Zfv/724/
There are many ways to do this. This is a clickhandler (plain js) for a div containing a number of checkboxes:
function cbclick(e){
e = e || event;
var cb = e.srcElement || e.target;
if (cb.type !== 'checkbox') {return true;}
var cbxs = document.getElementById('radiocb')
.getElementsByTagName('input'),
i = cbxs.length;
while(i--) {
if (cbxs[i].type
&& cbxs[i].type == 'checkbox'
&& cbxs[i].id !== cb.id) {
cbxs[i].checked = false;
}
}
}
Here's a working example.
This is a better option as it allows unchecking also:
$(".cb").change(function () {
$(".cb").not(this).prop('checked', false);
});
I kept it simple...
<html>
<body>
<script>
function chbx(obj)
{
var that = obj;
if(document.getElementById(that.id).checked == true) {
document.getElementById('id1').checked = false;
document.getElementById('id2').checked = false;
document.getElementById('id3').checked = false;
document.getElementById(that.id).checked = true;
}
}
</script>
<form action="your action" method="post">
<Input id='id1' type='Checkbox' Name ='name1' value ="S" onclick="chbx(this)"><br />
<Input id='id2' type='Checkbox' Name ='name2' value ="S" onclick="chbx(this)"><br />
<Input id='id3' type='Checkbox' Name ='name3' value ="S" onclick="chbx(this)"><br />
<input type="submit" value="Submit" />
</form>
</body>
</html>
#DJafari's answer doesn't let unchecking the checkbox. So I've updated it like this:
$(".chb").change(function(e) {
//Getting status before unchecking all
var status = $(this).prop("checked");
$(".chb").prop('checked', false);
$(this).prop('checked', true);
//false means checkbox was checked and became unchecked on change event, so let it stay unchecked
if (status === false) {
$(this).prop('checked', false);
}
});
https://jsfiddle.net/mapetek/nLtb0q1e/4/
Just in case it helps someone else
I was having the same situation where my client needed to have a checkbox behaving like a radio button. But to me it was meaningless to use a checkbox and make it act like radio button and it was very complex for me as I was using so many checkboxes in a GridView Control.
My Solution: So, I styled a radio button look like a checkbox and took the help of grouping of radio buttons.
You could give the group of checkboxes you need to behave like this a common class, then use the class to attach the following event handler:
function clickReset ()
{
var isChecked = false,
clicked = $(this),
set = $('.' + clicked.attr ('class') + ':checked').not (clicked);
if (isChecked = clicked.attr ('checked'))
{
set.attr ('checked', false);
}
return true;
}
$(function ()
{
$('.test').click (clickReset);
});
Note: This is pretty me just shooting from the hip, I've not tested this and it might need tweaking to work.
I would advise that you do look into finding a way of doing this with radio buttons if you can, as radios are the proper tool for the job. Users expect checkboxes to behave like checkboxes, not radios, and if they turn javascript off they can force through input into the server side script that you weren't expecting.
EDIT: Fixed function so that uncheck works properly and added a JS Fiddle link.
http://jsfiddle.net/j53gd/1/
<html>
<body>
<form action="#" method="post">
Radio 1: <input type="radio" name="radioMark" value="radio 1" /><br />
Radio 2: <input type="radio" name="radioMark" value="radio 2" /><br />
<input type="submit" value="Submit" />
</form>
</body>
</html>
Ultimately you can use brackets with the name attribute to create an array of radio input like so:
<input type="radio" name="radioMark[]" value="radio1" />Radio 1
<input type="radio" name="radioMark[]" value="radio2" />Radio 2
<input type="radio" name="radioMark[]" value="radio3" />Radio 3
<input type="radio" name="radioMark[]" value="radio4" />Radio 4
What matters to transfer in the end are whats in the value attribute. Your names do not have to be different at all for each radio button. Hope that helps.
In Simple JS.
Enjoy !
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function onChoiceChange(obj) {
// Get Objects
var that=obj,
triggerChoice = document.getElementById(that.id),
domChoice1 = document.getElementById("Choice1"),
domChoice2 = document.getElementById("Choice2");
// Apply
if (triggerChoice.checked && triggerChoice.id === "Choice1")
domChoice2.checked=false;
if (triggerChoice.checked && triggerChoice.id === "Choice2")
domChoice1.checked=false;
// Logout
var log = document.getElementById("message");
log.innerHTML += "<br>"+ (domChoice1.checked ? "1" : "0") + ":" + (domChoice2.checked ? "1" : "0");
// Return !
return that.checked;
}
</script>
</head>
<body>
<h1 id="title">Title</h1>
<label><input type="checkbox" onclick="onChoiceChange(this)" id="Choice1" />Choice #1</label>
<label><input type="checkbox" onclick="onChoiceChange(this)" id="Choice2" />Choice #2</label>
<hr>
<div id="message"></div>
</body>
</html>
try this
<form id="form" action="#">
<input name="checkbox1" type="checkbox" />
<input name="checkbox2" type="checkbox" />
<input name="checkbox3" type="checkbox" />
<input name="checkbox4" type="checkbox" />
<input name="checkbox5" type="checkbox" />
<input name="checkbox6" type="checkbox" />
<input name="checkbox7" type="checkbox" />
<input name="checkbox8" type="checkbox" />
<input name="checkbox9" type="checkbox" />
<input name="checkbox10" type="checkbox" />
<input type="submit" name="submit" value="submit"/>
</form>
and this is the javascript
(function () {
function checkLikeRadio(tag) {
var form = document.getElementById(tag);//selecting the form ID
var checkboxList = form.getElementsByTagName("input");//selecting all checkbox of that form who will behave like radio button
for (var i = 0; i < checkboxList.length; i++) {//loop thorough every checkbox and set there value false.
if (checkboxList[i].type == "checkbox") {
checkboxList[i].checked = false;
}
checkboxList[i].onclick = function () {
checkLikeRadio(tag);//recursively calling the same function again to uncheck all checkbox
checkBoxName(this);// passing the location of selected checkbox to another function.
};
}
}
function checkBoxName(id) {
return id.checked = true;// selecting the selected checkbox and maiking its value true;
}
window.onload = function () {
checkLikeRadio("form");
};
})();
I like D.A.V.O.O.D's Answer to this question, but it relies on classes on the checkbox, which should not be needed.
As checkboxes tend to be related in that they will have the same (field) name, or a name which make them part of an array, then using that to decide which other checkboxes to untick would be a better solution.
$(document)
.on('change','input[type="checkbox"]',function(e){
var $t = $(this);
var $form = $t.closest('form');
var name = $t.attr('name');
var selector = 'input[type="checkbox"]';
var m = (new RegExp('^(.+)\\[([^\\]]+)\\]$')).exec( name );
if( m ){
selector += '[name^="'+m[1]+'["][name$="]"]';
}else{
selector += '[name="'+name+'"]';
}
$(selector, $form).not($t).prop('checked',false);
});
This code on jsFiddle

Categories

Resources