Linking checkboxes to text inputs and updating its fields - javascript

I am trying to link a checkbox to a text input in order to update the value inside the input field.
My problem is how do I update the value accordingly when the checkbox is ticked. For example, I would like to have a text stating status is "Pending" (with the checkbox unticked) and once the box is ticked, update the value to "Completed" and possibly highlight the text input to a green colour.
Picture:
Code:
<div class="status-updates">
<label class="radio" for="status-updates">
<input type="checkbox" name="status" id="statuses">
</label>
<input type="text" name="pending-completed" id="pending-completed" class="pending-completed" placeholder="Pending">
</div>
Do I need some sort of jQuery to run some sort of input validation?
Would appreciate some help on this.
Thank you.

Try below jquery code(bind .change() event of checkbox) :-
$('#statuses').change(function(){
if($(this).is(':checked'))
{
$("#pending-completed").attr('placeholder','Completed')
}
else
{
$("#pending-completed").attr('placeholder','Pending')
}
});
EDIT(Placeholder with green color) :-
Jquery :
$('#statuses').change(function(){
if($(this).is(':checked'))
{
$("#pending-completed").attr('placeholder','Completed').addClass('green-class')
}
else
{
$("#pending-completed").attr('placeholder','Pending').removeClass('green-class')
}
});
CSS :
.green-class::-webkit-input-placeholder {
color: green;
}
DEMO

Try this : bind change event to checkbox and put placeholder as per checkbox checked status.
$(function(){
$('#statuses').change(function(){
var placeholder = $(this).is(':checked')?"Completed":"Pending";
$("#pending-completed").attr('placeholder',placeholder);
});
});

LIVE DEMO: http://jsfiddle.net/don/qaxow1jz/
jQuery:
$('input[name=status]').change(function() {
var inputText = 'input[name=pending-completed]';
if($(this).is(':checked')) {
$(inputText).attr('placeholder', 'Completed').addClass('highlight');
} else {
$(inputText).attr('placeholder', 'Pending').removeClass('highlight');
}
});
HTML:
<div class="status-updates">
<label class="radio" for="status-updates">
<input type="checkbox" name="status" id="statuses">
</label>
<input type="text" name="pending-completed" id="pending-completed" class="pending-completed" placeholder="Pending">
</div>
CSS:
input.highlight[name=pending-completed]::-webkit-input-placeholder {
color: green;
}
input.highlight[name=pending-completed]:-moz-placeholder {
color: green;
}
input.highlight[name=pending-completed]::-moz-placeholder {
color: green;
}
input.highlight[name=pending-completed]:-ms-input-placeholder {
color: green;
}

Have a look at this . Working example : http://jsfiddle.net/gmwzzL10/
HTML
<div class="status-updates">
<label class="radio" for="status-updates">
<input type="checkbox" name="status" id="statuses" class="checkbox_status">
</label>
<input type="text" name="pending-completed" id="pending-completed" class="pending-completed" placeholder="Pending">
</div>
JS
$("document").ready(function(){
$(".checkbox_status").click(function(){
var inputBox = $(this).closest(".status-updates").find(".pending-completed");
if($(this).is(':checked')){
inputBox.attr("placeholder","Completed").addClass("make-green");
}
else{
inputBox.attr("placeholder","Pending").removeClass("make-green");
}
})
})
CSS
.make-green{
border: 1px solid green;
}

Related

How do I validate a radio button with JavaScript?

How do I validate a radio button? I want to make it so that if the user left the radio button unclicked the section background will turn a red colour/color.
Here is the HTML Page
<p id="caption_project">Project Selection
<br/>
<input type="radio" name="f__project" id="in_restaurant" value="restaurant"/>
<label for="in_restaurant">LEGO Project</label>
<br/>
<input type="radio" name="f__project" id="in_humber" value="Humber News"/>
<label for="in_humber">Humber Current Project</label>
<br/>
<input type="radio" name="f__project" id="in_self" value="self-determined"/>
<label for="in_self">Self-determined Project</label>
</p>
So how do I turn the background red when they leave it unchecked?
You need to think of some event the user will fire which you want to trigger the function that makes the background go red. That could be if the user clicks on the next form control. Then when that event fires you test whether they checked any radio buttons. If they did not (!checked) then you set the style attribute of your p element to background:red:
const nextThing = document.querySelector('#next-thing');
const p = document.querySelector('p');
nextThing.addEventListener('click', function(){
const checked = document.querySelector("input[name='f__project']:checked");
if(!checked){
p.setAttribute('style', 'background:red');
}
});
<p id="caption_project">Project Selection
<br/>
<input type="radio" name="f__project" id="in_restaurant" value="restaurant"/>
<label for="in_restaurant">LEGO Project</label>
<br/>
<input type="radio" name="f__project" id="in_humber" value="Humber News"/>
<label for="in_humber">Humber Current Project</label>
<br/>
<input type="radio" name="f__project" id="in_self" value="self-determined"/>
<label for="in_self">Self-determined Project</label>
</p>
<button id='next-thing'>Next form control</button>
Use document.querySelector("input[name='f__project']:checked"). If this returns null, none of the radio buttons were checked, and you can display the red background.
If this is in a <form> you can add the required attribute to the radio buttons. If they try to submit the form without selecting one of them, the browser will display a validation error.
Use document.getElementById('id').checkedthe statement returns True or False.
const checkedRadioButton = document.
querySelector("input[name='f__project']:checked");
if (!checkedRadioButton) {
// No values are selected
} else {
// Some value is selected and the element is stored in checkedRadioButton
}
You can use CSS to manipulate the colour depending on whether the radio input is checked or not.
input[type="radio"] {
display: none;
}
input[type="radio"] + label {
border: 5px solid lightblue;
background-color: lightblue;
cursor: pointer;
display: block;
height: 40px;
width: 200px;
text-align: center;
line-height: 40px;
}
input[type="radio"]:checked + label {
border: 5px solid blue;
background-color: dodgerblue;
}
Or else you can make a Javascript function to check
function checkRadioValidity() {
if(document.getElementById('in_restaurant').checked) {
//change CSS here for the element
}
}
The idea of radio button is that it can not be unchecked.
EDIT:
document.querySelector("input[name='f__project']:checked")
will return element if it is checked

check if all inputs are checked

I have 2 buttons and 2 inputs. The "buy"-button should only fire its default function when both inputs are checked. If not it should mark them with a red border. What am I doing wrong here?
jQuery(function($) {
$('.checkedterms:checked').length == $('.checkedterms').length
$("#upsellyes").click(function(e) {
$(".checkedterms").change(function(){
if (!$('.checkedterms:checked').length == $('.checkedterms').length) {
e.preventDefault();
$("#terms-required").addClass('invalid');
}
else {
$("#terms-required").removeClass('invalid');
}
});
});
});
.invalid {
border: 1px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="terms-required">
<input type="checkbox" class="checkedterms" name="terms" id="terms" style="position: absolute;"><label for="terms" class="checkbox" style="display: inline-block!important;font-weight:normal!important;margin-left: 25px;">I have read <a href="#" >Allgemeinen Geschäftsbedingungen</a>.<span class="required">*</span></label><br />
<input type="checkbox" class="checkedterms" name="terms" id="terms" style="position: absolute;"><label for="terms" class="checkbox" style="display: inline-block!important;font-weight:normal!important;margin-left: 25px;">I have read <a href="#" >Widerrufsbelehrung</a>.<span class="required">*</span></label><br />
</div><br>
buy<br><br>
no thanks
There's a couple of issues here:
You've got an equality check at the start of the code which does nothing.
You've nested the change handler on the checkboxes within the click handler of the button; remove it.
Unrelated to the issue, but you are using duplicate id attributes. They need to be unique within the DOM.
Your logic is backwards. You state that you want the red border to only appear when both checkboxes are not checked when the 'Buy' button is clicked.
You can also make the logic more succinct by caching the checkbox selector and using toggleClass(). Something like this:
jQuery(function($) {
$("#upsellyes").click(function(e) {
var $terms = $('.checkedterms');
$("#terms-required").toggleClass('invalid', $terms.length != $terms.filter(':checked').length);
});
});
.invalid {
border: 1px solid red;
}
.checkedterms {
position: absolute;
}
label {
display: inline-block!important;
font-weight: normal!important;
margin-left: 25px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="terms-required">
<input type="checkbox" class="checkedterms" name="terms" />
<label for="terms" class="checkbox">
I have read Allgemeinen Geschäftsbedingungen.
<span class="required">*</span>
</label><br />
<input type="checkbox" class="checkedterms" name="terms" />
<label for="terms" class="checkbox">
I have read <a href="#" >Widerrufsbelehrung</a>.
<span class="required">*</span>
</label><br />
</div><br />
buy<br><br>
no thanks
Finally note the use of a separate stylesheet. Inline styling is a bad idea and should be avoided where possible.
remove this line
$(".checkedterms").change(function(){ //remove
//keep the code that's currently here
}); //remove
leaving you with
jQuery(function($) {
$('.checkedterms:checked').length == $('.checkedterms').length
$("#upsellyes").click(function(e) {
if ($('.checkedterms:checked').length != $('.checkedterms').length) {
e.preventDefault();
$("#terms-required").addClass('invalid');
}
else {
$("#terms-required").removeClass('invalid');
}
});
});
the code wasn't running because you were setting an event listener on the checkboxes inside the event listener on the button. what was happening is that when you clicked the button, javascript would set an event listener on the checkboxes that fires when their state changes
You need an if statement at line 2 and one more '='
if ($('.checkedterms:checked').length === $('.checkedterms').length) {
....
}
and you should put an eventListener each input change

jquery, js. custom text color

How can i change the color of the text inside input box to different color. eg. text to green, red, purple etc.. I planned to use select box to store the different color and based on the selected color change the "text" color: but I am having hard time implementing into code. I am new to js, jquery any help will be greatly appreciated. Also what needs to be done to get the text with selected color to a table(do i save the color in databse?). I will be very thankful to get any help on this .
I made a small demo based on your requirements. You can read the comments in the code.
Something like this:
(function() {
function get(id) {
return document.getElementById(id); // Return the element given an id.
}
var selColors = get("selColors"); // Store the context of the selColors element.
var txtMyText = get("txtMyText"); // Store the context of the txtMyText element.
var myForm = get("myForm"); // Store the context of the myForm element.
var selectedColor = get("selectedColor");
// This is an object that has 2 properties: (color and value). These properties can hold in it string values.
var obj = {
color: "",
value: ""
};
// When you select an option.
selColors.onchange = function() {
if (this.value.length > 0) {
obj.color = this.value; // this.value contains the color that you have selected.
selectedColor.setAttribute("style", "background-color: " + obj.color);
txtMyText.setAttribute("style", "color: " + this.value); // With this you can set a style to the txtMyText textbox.
}
};
// When you submit the form.
myForm.onsubmit = function(e) {
obj.value = txtMyText.value;
console.log(obj); // Shows in the console the object with the current color and value of your textbox.
e.preventDefault();
};
})();
#myForm {
border: solid 1px #335a82;
}
#myForm fieldset {
border: solid 1px #a3c9d4;
}
#myForm fieldset div {
margin: 5px;
}
#myForm fieldset div label {
display: inline-block;
width: 120px;
}
#selectedColor {
display: inline-block;
padding: 10px;
width: 120px;
}
<form id="myForm">
<fieldset>
<legend>Configuration</legend>
<div>
<label>Colors:</label>
<select id="selColors">
<option value="">[Select a color]</option>
<option value="#5069b1">#5069b1</option>
<option value="#ff0000">#ff0000</option>
<option value="#841b72">#841b72</option>
</select>
</div>
<label>Selected color:</label>
<div id="selectedColor">
</div>
</fieldset>
<fieldset>
<legend>Preview</legend>
<div>
<label>Text:</label>
<input id="txtMyText" type="text" />
</div>
<div>
<button type="submit">Send</button>
</div>
</fieldset>
</form>
You could use js to select the class or id of the <input class=".." id="..">
Then you would be able to change the CSS attributes with js.
See the following example
<form method="post">
<input type="text" class="input1">
</form>
So your <input> class is input1. Using the following CSS code you could select a class by its name. See the example below
<script>
function myFunction() {
var x = document.getElementsByClassName("example");
}
</script>
Now by adding a CSS atribute like color to the function you could change the existing or add a new CSS rule to your <input> field.
I think you could get pretty far with this example.
Let me know if it helps!
$('#myinput').css("color","#fdd");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" value="test" id="myinput">
You could try this also:
$('#myinput').css('color',$('#myinput').val());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" value="#04edee" id="myinput" onkeyup="$('#myinput').css('color',$('#myinput').val());">
jQuery option to show some fun stuff:
$(function() {
$('#myColors').on('change', function() {
var picked = $(this).val();
$('#currentcolor').css("background-color", picked);
$('#results').append("<div>" + $(this).find("option:selected").text() + "|" + picked + "</div>");
});
// verbose add on click of button
$('#addHot').on('click', function() {
var valHot = '#69b4ff';
var newName = "Hot Pink Triadic Blue";
//$('#myColors').append("<option value='"+valHot+" style='color:"+nameHot+"'>"+nameHot+"</option>");
var newOpt = $("<option></option>");
newOpt.css("color:" + valHot);
newOpt.prop("value", valHot);
newOpt.text(newName);
newOpt.appendTo('#myColors');
console.log(newOpt);
});
});
<div>
<select id="myColors">
<option value="red" style="color:red">Red</option>
<option value="green" style="color:green">Green</option>
<option value="cyan" style="color:cyan">Cyan</option>
<option value="#0080ff" style="color:#0080ff">Analogous Cyan</option>
</select>
<button id="addHot" type="button">
Add Hot Pink Triadic Blue
</button>
</div>
<div>
<div id="currentcolor">
current color is background
</div>
<div id="results">
Show stuff:
</div>
</div>
What you can do create class for every color like .green .purple and just remove and add classes
$(".input1").addClass("red").removeClass("green");
and you can also add remore these classes with selected box color change

Change parent div if input radio is checked

I have 3 radio inputs, that are wrapped in div so that they look like buttons instead of the default radio circle input, on click I am replacing the button text for checked icon. Now on validation if it fails I am returning the old value, and would like to again replace the text of the button for icon checked if the radio input was checked.
This is the script for the click action:
$('.Image-input__input-wrapper').click(function() {
$( '.plan-text-icon-toggle' ).replaceWith( '<span class="plan-text-icon-toggle">This is what I need</span>' )
$(this).find( '.plan-text-icon-toggle' ).replaceWith( '<span class="plan-text-icon-toggle"><i class="ion-checkmark-round"></i></span>' );
});
This is the html:
<div class="Image-input__input-wrapper">
<span class="plan-text-icon-toggle">This is what I need</span>
<input class="Image-input__input" type="radio" name="plan" value="player" {{ old('plan')=="player" ? 'checked='.'"'.'checked'.'"' : '' }}>
</div>
Now I would like to to do same for on page load if the button was checked already, but not sure how to do it?
Update
I have tried with adapting the suggestion in the answers:
function checkinput(elem) {
var parent = elem.parent(),
checked = elem.is(':checked');
$('.radio').removeClass('active').html('This is what I need');
if (checked) {
parent.addClass('active').html('Checked');
}
}
// apply style on change
$('[type=radio]').on('change', function () {
var elem = $(this);
checkinput(elem);
});
// apply style on load
var elem = $('[type=radio]:checked');
checkinput(elem);
Here is the full example. But it is not working.
You can always use input radio and just change the style with CSS. Look the example bellow:
function checkinput(elem) {
var parent = elem.parent(),
checked = elem.is(':checked');
$('.radio').removeClass('active');
if (checked) {
parent.addClass('active');
}
}
// apply style on change
$('[type=radio]').on('change', function () {
var elem = $(this);
checkinput(elem);
});
// apply style on load
var elem = $('[type=radio]:checked');
checkinput(elem);
.radio .on {
display: none;
}
.radio.active .off {
display: none;
}
.radio.active .on {
display: inline;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<label class="radio">
<span class="on">Message when checked</span>
<span class="off">Message when unchecked</span>
<input type="radio" name="my-radio" value="1">
</label>
</div>
<div>
<label class="radio">
<span class="on">Message when checked</span>
<span class="off">Message when unchecked</span>
<input type="radio" name="my-radio" value="2">
</label>
</div>
<div>
<label class="radio">
<span class="on">Message when checked</span>
<span class="off">Message when unchecked</span>
<input type="radio" name="my-radio" value="3" checked>
</label>
</div>

jquery - show textbox when checkbox checked

I have this form
<form action="">
<div id="opwp_woo_tickets">
<input type="checkbox" class="maxtickets_enable_cb" name="opwp_wootickets[tickets][0][enable]">
<div class="max_tickets">
<input type="text" name="opwp_wootickets[tickets][0][maxtickets]">
</div>
<input type="checkbox" class="maxtickets_enable_cb" name="opwp_wootickets[tickets][1][enable]">
<div class="max_tickets">
<input type="text" name="opwp_wootickets[tickets][1][maxtickets]">
</div>
<input type="checkbox" class="maxtickets_enable_cb" name="opwp_wootickets[tickets][2][enable]">
<div class="max_tickets">
<input type="text" name="opwp_wootickets[tickets][2][maxtickets]">
</div>
</div>
</form>
As of now, I'm using this jquery code to show textbox when checkbox checked.
jQuery(document).ready(function($) {
$('input.maxtickets_enable_cb').change(function(){
if ($(this).is(':checked')) $('div.max_tickets').show();
else $('div.max_tickets').hide();
}).change();
});
It works fine, but it shows all textboxes when checked.
Can someone help me to fix it?
Here is the demo of my problem.
http://codepen.io/mistergiri/pen/spBhD
As your dividers are placed next to your checkboxes, you simply need to use jQuery's next() method to select the correct elements:
if ($(this).is(':checked'))
$(this).next('div.max_tickets').show();
else
$(this).next('div.max_tickets').hide();
Updated Codepen demo.
From the documentation (linked above), the next() method selects:
...the immediately following sibling of each element in the set of matched elements. If a selector is provided, it retrieves the next sibling only if it matches that selector.
Here we're selecting the next div.max_tickets element. However in your case just using next() with no parameters would suffice.
Assuming markup will stay in same order can use next()
jQuery(document).ready(function($) {
$('input.maxtickets_enable_cb').change(function(){
$(this).next()[ this.checked ? 'show' : 'hide']();
}).change();
});
Change:
if ($(this).is(':checked')) $('div.max_tickets').show();
To:
if ($(this).is(':checked')) $(this).next('div.max_tickets').show();
jsFiddle example here
Maybe try selecting the next element only?
change:
if ($(this).is(':checked')) $('div.max_tickets').show();
to:
if ($(this).is(':checked')) $(this).next('div.max_tickets').show();
Put a div across your checkbox and text box
<form action="">
<div id="opwp_woo_tickets">
<div>
<input type="checkbox" class="maxtickets_enable_cb" name="opwp_wootickets[tickets][0][enable]">
<div class="max_tickets">
<input type="text" name="opwp_wootickets[tickets][0][maxtickets]">
</div>
</div>
<div>
<input type="checkbox" class="maxtickets_enable_cb" name="opwp_wootickets[tickets][1][enable]">
<div class="max_tickets">
<input type="text" name="opwp_wootickets[tickets][1][maxtickets]">
</div>
</div>
<div>
<input type="checkbox" class="maxtickets_enable_cb" name="opwp_wootickets[tickets][2][enable]">
<div class="max_tickets">
<input type="text" name="opwp_wootickets[tickets][2][maxtickets]">
</div>
</div>
</div>
</form>
and replace your jquery code with this one below,
jQuery(document).ready(function($) {
$('input.maxtickets_enable_cb').change(function(){
if ($(this).is(':checked')) $(this).parent().children('div.max_tickets').show();
else $(this).parent().children('div.max_tickets').hide();
}).change();
});
I have tested it and it works.
While you may need a JavaScript solution for other reasons, it's worth noting that this can be achieved with pure CSS:
input + div.max_tickets {
display: none;
}
input:checked + div.max_tickets {
display: block;
}
JS Fiddle demo.
Or, with jQuery, the simplest approach seems to be:
// binds the change event-handler to all inputs of type="checkbox"
$('input[type="checkbox"]').change(function(){
/* finds the next element with the class 'max_tickets',
shows the div if the checkbox is checked,
hides it if the checkbox is not checked:
*/
$(this).next('.max_tickets').toggle(this.checked);
// triggers the change-event on page-load, to show/hide as appropriate:
}).change();
JS Fiddle demo.
Reference:
CSS:
:checked pseudo-class.
jQuery:
change().
next().
toggle().
protected void EnableTextBox()
{
int count = int.Parse(GridView1.Rows.Count.ToString());
for (int i = 0; i < count; i++)
{
CheckBox cb = (CheckBox)GridView1.Rows[i].Cells[0].FindControl("CheckBox1");
CheckBox cb1 = (CheckBox)GridView1.Rows[i].Cells[0].FindControl("CheckBox2");
CheckBox cb2 = (CheckBox)GridView1.Rows[i].Cells[0].FindControl("CheckBox3");
TextBox tb = (TextBox)GridView1.Rows[i].Cells[4].FindControl("txtration");
TextBox tb1 = (TextBox)GridView1.Rows[i].Cells[5].FindControl("txtjob");
TextBox tb2 = (TextBox)GridView1.Rows[i].Cells[6].FindControl("txtaadhar");
if (cb.Checked == true)
{
tb.Visible = true;
}
else
{
tb.Visible = false;
}
if (cb1.Checked == true)
{
tb1.Visible = true;
}
else
{
tb1.Visible = false;
}
if (cb2.Checked == true)
{
tb2.Visible = true;
}
else
{
tb2.Visible = false;
}
}
}
protected void CheckBox1_CheckedChanged(object sender, EventArgs e)
{
EnableTextBox();
}

Categories

Resources