Check Box Disablement On Page Reload Jscript - javascript

When I select the boxes, I want the text fields to become editable. At first it works but if I reload the page with the boxes checked, it will do the opposite of what it is supposed to do (i.e. after page is reloaded, when the boxes aren't checked, the text fields are editable; when checked, they become un-editable)
<table>
<tr>
<td>
<input type="checkbox" name="Download_Limit" value="download" class="checkme"/>Download Limit
<br/>
<input type="text" name="download" class="text required" id="Download_Input" size="3">
<label class="description" for="Expire">Downloads</label>
</td>
</tr>
<tr>
<td>
<input type="checkbox" name="Time_Limit" value="time" class="checkme"/>Time Limit
<br/>
<input type="text" name="time" class="text required" id="Time_Input" size="3">
<label class="description" for="Expire">Hours</label>
</td>
</tr>
My Javascript
$('.checkme').attr('checked', false);
$('.checkme').click(function(){
if($('input[name='+ $(this).attr('value')+']').attr('disabled') == false){
$('input[name='+ $(this).attr('value')+']').attr('disabled', true);
}else{
$('input[name='+ $(this).attr('value')+']').attr('disabled', false);
}
});

Here is what I would do. First, setup all the default values that you want:
// Set default page values on load...
$('.checkme').prop('checked', false);
$('input[type="text"]').prop('disabled', true).val('');
// Then setup events...
$('.checkme').on('click', function () {
var $this = $(this);
if($('input[name='+ $this.val() +']').prop('disabled')){
$('input[name='+ $this.val()+']').prop('disabled', false);
} else {
$('input[name='+ $this.val()+']').prop('disabled', true);
}
});
We've changed a few things up here. Let me explain.
First, we've changed .attr('checked'...) and .attr('disabled'...) to use .prop() instead. checked and disabled are properties not attributes.
We're now attaching the event using .on(). This is just the method I prefer, however simply doing .click() will work as well.
We're saving off the element into a local variable $this first thing. This keeps jQuery from having to re-traverse the DOM multiple times within the same function.
I've simplified .attr('value') to the shorthand .val().
Lastly, we've simplified your if statement by removing the negative condition and allowing JavaScript to use the truthy/falsy conditionals.
Fiddle
A Few Other Notes:
I know it is a traditional method of page layout, but I highly discourage using tables to position elements. It is not the appropriate use of tables and results in a page layout that is not semantically correct. Check out the <div> and <span> elements to layout your code and try styling it to appear the way you want with CSS.
Also, it appears you are formatting your HTML in the XHTML syntax. That is perfectly fine, however I recommend that you be consistent when closing tags. Two of your <input /> element tags are not closed properly.
// This...
<input type="text" name="download" class="text required" id="Download_Input" size="3">
// Should be this...
<input type="text" name="download" class="text required" id="Download_Input" size="3" />
// And this...
<input type="text" name="time" class="text required" id="Time_Input" size="3">
// Should be this...
<input type="text" name="time" class="text required" id="Time_Input" size="3" />
Make sure you are consistent in your methods of markup. Inconsistencies such as this will result in an invalid markup.
Finally, I do not believe that you can have <tr> elements nested directly inside of a <table> element. I believe they have to be inside of a <thead>, <tbody> or <tfoot> element. Again, leaving out elements such as these results in invalid markup.

Try this DEMO . I think it's more elegant.
$('.checkme').click(function() {
var input = $(this).closest('td').find('input[type="text"]');
if (input.is(':disabled')){
input.attr('disabled', false);
}else{
input.attr('disabled', true);
}
});
Also, your input type="text" mark up should be disabled as follows:
<input type="text" disabled="disabled" name="time" class="text required" id="Time_Input" size="3" />

Related

how to toggle multiple inputs within a table depending on radio button selection

Assume the following html:
<tr>
<td>
<label for="c1_testRdio">Have you taken any tests in this class?:</label>
<br>
<label>Yes<input type="radio" class="testRdio" name="c1_testRdio" value="Yes"></label>
<label>No <input type="radio" class="testRdio" name="c1_testRdio" value="No" checked></label>
<label>How Many? <input type="text" class="howManyTests" name="c1_howManyTests" disabled></label>
</td>
<td>
<label for="c1_whatGradesTests">What were your grades?:</label><br>
<input type="text" name="c1_whatGradesTests" disabled>
</td>
</tr>
if radio with value="Yes" is selected, what jQuery (1.5 compatible ) code would enable the 2 text inputs, c1_howManyTests and c1_whatGradesTests?
Have tried:
$('.testRdio').change(function(){
//var txt = $(this).closest("td").next("td").children('.howManyTests');
var txt = $(this).parent().next('label>input[type="text"]');
console.log(txt.id);
this.value == 'No' ? txt.removeAttr('disabled') : txt.attr('disabled', 'disabled');
});
Try this:
$('.testRdio').change(function () {
$(this).closest('tr').find('input[type="text"]').attr('disabled', this.value === 'No');
});
The older jq version that doesnot have prop, attr (used to do the job of prop as well) used to take bool values for disabled.
Demo
Also i had to fix your markup a lot as well (Now i see its fixed in the question already)
$('.testRdio').change(function(){
$(this).closest('tr').find('input[type="text"]').attr('disabled',$(this).val()=="No");
});
jsFiddle example
Your code was a little messy, so I rebuilt it: http://jsfiddle.net/QgJac/1/
I think hiding the whole div is better. They don't really need to see those questions if they select 'No'.

Enabling text fields based on radio button selection

Basically, I have two radio button 'yes' and 'no' and then a further two input fields.
[LabelQuestion] [RadioYes][RadioNo]
If yes, then... [TextField1]
If no, then... [TextField2]
By default I would like to have text fields 1 and 2 inactive/not able to enter in data until the relevant radio button has been selected and then that field only becomes available for data input.
I am a complete novice but I imagine this is achievable by using CSS and/or JavaScript. Please bear in mind I have next to know knowledge of JavaScript but can logically alter pre-existing JS code.
My current code looks like this:
<div class='conlabel'>Have you started trading yet?</div>
<table width="100">
<tr>
<td><label>
<input type="radio" name="example" value="Yes" id="example_0" required/>
Yes</label></td>
</tr>
<tr>
<td><label>
<input type="radio" name="example" value="No" id="example_1" required/>
No</label></td>
</tr>
</table>
<li>
<div class='conlabel'>If Yes, then:</div>
<input type="text" name="field1" placeholder="" />
</li><br>
<div class='conlabel'>If No, then:</div>
<input type="text" name="field2" placeholder="" />
</li><br>
How about this little number:
$(function(){
$("#example_0, #example_1").change(function(){
$("#field1, #field2").val("").attr("readonly",true);
if($("#example_0").is(":checked")){
$("#field1").removeAttr("readonly");
$("#field1").focus();
}
else if($("#example_1").is(":checked")){
$("#field2").removeAttr("readonly");
$("#field2").focus();
}
});
});
You'll find a JSFiddle here.
Please note I've added an ID to both <input> fields. Let me know how it fairs.
If you prefer for the <input> fields to be disabled rather than readonly, just replace readonly with disabled everywhere. I personally think readonly is nicer as the Operating System seems to make more of it's own effect on disabled inputs.
The focus(), of course, isn't necessary - But the little things make a big difference and I always prefer it when a website moves my cursor to where it's expected to be for me.
You could use http://jquery.com/ to do this:
include this in the head of your html:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
And also add this javascript:
<script type="text/javascript">
$(document).ready(function () {
function checkradiobox(){
var radio = $("input[name='example']:checked").val();
$('#field1, #field2').attr('disabled',true);
if(radio == "Yes"){
$('#field1').attr('disabled',false);
$("#field1").focus();
}else if(radio == "No"){
$('#field2').attr('disabled',false);
$("#field2").focus();
}
}
$("#example_0, #example_1").change(function () {
checkradiobox();
});
checkradiobox();
});
</script>
Check the jsfiddle for a working example http://jsfiddle.net/KFgbg/3/
Add this javascript/jQuery to your html, this should do the trick:
<script type="text/javascript">
$(function () {
// First add disabled properties to inputs
$("input:text").prop('disabled', true);
// Yes Input
$("#example_0").on("click", function () {
$("#input1").prop('disabled', false);
$("#input2").prop('disabled', true);
});
// No Input
$("#example_1").on("click", function () {
$("#input2").prop('disabled', false);
$("#input1").prop('disabled', true);
});
});
</script>
Very basic, just adds an onclick function to each of the inputs and enables or disables the 'disabled' property for the relevant text input. You will need to add the "#input1" and "#input2" ID's to the text inputs, naming can be as desired obviously.
<div class='conlabel'>Have you started trading yet?</div>
<table width="100">
<tr>
<td><label>
<input onclick="document.getElementById('field1').disabled=false;document.getElementById('field2').disabled=true;"" type="radio" name="example" value="Yes" id="example_0" required/>
Yes</label></td>
</tr>
<tr>
<td><label>
<input onclick="document.getElementById('field1').disabled=true;document.getElementById('field2').disabled=false;" type="radio" name="example" value="No" id="example_1" required/>
No</label></td>
</tr>
</table>
<li>
<div class='conlabel'>If Yes, then:</div>
<input type="text" id="field1" name="field1" placeholder="" disabled="true" />
</li><br>
<div class='conlabel'>If No, then:</div>
<input type="text" id="field2" name="field2" placeholder="" disabled="true" />
there are many ways to do this, but to edit your code as little as possible, here's one way:
give your textboxes ID attributes as well as names
disable via html attribute both text boxes to start
onclick of 'yes' radio button, enable field1 and disable field2
onclick of 'no' radio button, disable field1 and enable field2
<script language="Javascript">
function hideA()
{
document.getElementById("A").style.visibility="hidden";
document.getElementById("B").style.visibility="visible";
}
function hideB()
{
document.getElementById("B").style.visibility="hidden";
document.getElementById("A").style.visibility="visible";
}
</script>
</head>
<body>
<form name="f1" method="post" action="">
<table>
<tr><th>catagory</th><th><input type="radio" name="cat" value="seller"
onClick="hideB()">Seller
<input type="radio" name="cat" value="buyer" onclick="hideA()"> buyer</th>
</tr>
<div style="position: absolute; left: 30px; top: 100px;visibility:hidden" id="A">
Seller Name<input type='text' name='sname'><br>
Seller Product<input type='text' name='sproduct'>
</div>
<div style="position: absolute; left: 30px; top: 100px; visibility:hidden" id="B">
Buyer Name<input type='text' name='bname'><br>
Buy Product<input type='text' name='bproduct'>
</div>
</form>

Trouble filling Multiple Textbox values from other Textboxes when Checkbox is Clicked

I DID search but couldn't find anything that helped me to figure out my particular issue. I've got textboxes for a customer address, and textboxes for a business address, and a checkbox to mark if the address should be the same. I need to get the Checkbox to fill the business address with the customer address onclick and unfill them on onclick. I've tried using a few different ways with jquery and straight javascript DOM manipulation, the most success I've had is in the following code, it only fills the biz_street textbox with the cust_street value though, and I don't understand why. Some help would be greatly appreciated, either in jquery or straight javascript, can't use php (sadly).
Here it is on jsfiddle (as suggested by rjmunro, good idea :) ): http://jsfiddle.net/yN73w/1/ not working at all
Here is the jquery:
$("#same_box").click(function () {
var v = $("#cust_street").val();
var x = $("#cust_city").val();
var y = $("#cust_state").val();
var z = $("#cust_zip").val();
$("#biz_street").val(v);
$("#biz_city").val(x);
$("#biz_state").val(y);
$("#biz_zip").val(z);
});
Or more simply:
$("#same_box").click(function () {
$("#biz_street").val($("#cust_street").val());
$("#biz_city").val($("#cust_city").val());
$("#biz_state").val($("#cust_state").val());
$("#biz_zip").val($("#cust_zip").val());
});
And the HTML:
<label id="cus_street_label">Street</label></br>
<input type="text" name="cust_street" id="cust_street" style="width:90%" /></br>
<div id="cus_city">
<label id="cus_city_label">City</label></br>
<input type="text" name="cust_city" id="cust_city" style="width:100%" /></br>
</div>
<div id="cus_state">
<label id="cus_state_label">State</label></br>
<input type="text" name="cust_state" id="cust_state" style="width:70%" /></br>
</div>
<div id="cus_zip">
<label id="cus_zip_label">Zip</label></br>
<input type="text" name="cust_zip" id="cust_zip" style="width:65%" /></br>
</div>
<input type="checkbox" name="same_box" id="same_box" >Address Same as Customer</input></br>
<label id="biz_street_label">Street</label></br>
<input type="text" name="biz_street" id="biz_street" style="width:90%" /></br>
<div id="biz_city">
<label id="biz_city_label">City</label></br>
<input type="text" name="biz_city_box" id="biz_city_box" style="width:100%" /></br>
</div>
<div id="biz_state">
<label id="biz_state_label">State</label></br>
<input type="text" name="biz_state_box" id="biz_state_box" style="width:70%" /></br>
</div>
<div id="biz_zip">
<label id="biz_zip_label">Zip</label></br>
<input type="text" name="biz_zip_box" id="biz_zip_box" style="width:80%" /></br>
</div>
Thank you very much for any help, and I apologize if I missed a topic like this in my searching.
(Also, unrelated, but why doesn't function formReset() {
document.getElementById("customer").reset();
} work in firefox? It only seems to work in chrome)
(you need to select jQuery in your JSFiddle, like http://jsfiddle.net/7HGNx/)
Your code is referring to biz_city but the element's id is biz_cty_box.
You probably don't want to attach to click, you probably want listen to the change event, as this will fire when the option is changed without the mouse. I would also check that the change has been ticking the box, not unticking the box.
$("#same_box").change(function (e) {
if ($(this).is(":checked")) {
.
.
.
}
}

Checkbox not unchecking visually

I have a form and within it is this:
<fieldset class="billing-address">
<legend>Billing Address</legend>
<ol>
<li class="text combi"><label for="bill-address1">Address:</label> <input size="20" value="" name="basket_order:default:bill_address1" id="bill-address1"></li>
<li class="text"><label for="bill-address2">Address:</label> <input size="20" value="" name="basket_order:default:bill_address2" id="bill-address2"></li>
<li class="text"><label for="bill-address3">Town/City:</label> <input size="20" value="" name="basket_order:default:bill_address3" id="bill-address3"></li>
<li class="text"><label for="bill-address4">Region:</label> <input size="20" value="" name="basket_order:default:bill_address4" id="bill-address4"></li>
<li class="text"><label for="bill-post-code">Post code:</label> <input size="10" value="" name="basket_order:default:bill_postcode" id="bill-post-code"></li>
</ol>
</fieldset>
For reasons too biring to go into here, I cannot get at the HTML directly and need to do things via javascript. So, I add a checkbox and label above using the following:
$('.billing-address ol').before('<input type="checkbox" id="billing-add-different" /><label for="billing-add-different">My billing address is the same as my delivery address</label>');
$('#billing-add-different').prop('checked',true).toggle(
function(){
$('.billing-address ol input, .billing-address ol select').css('background','#CCC').attr('disabled','disabled');
},
function(){
$('.billing-address ol input, .billing-address ol select').css('background','#FFF').removeAttr('disabled');
}
);
This toggles the 'disabled' attribute and background colour depending on whether it's ticked or not.
However, though the function is firing, the checkbox is still visually checked.
I've made a jsfiddle to illustrate at http://jsfiddle.net/EFQuh/. The error occurs in Firefox 8.0, not sure about others.
I don't know what is the problem (probably the toggle function), but you can simplify your code to:
$('#billing-add-different').prop('checked',true).change(function(){
$('.billing-address ol input, .billing-address ol select')
.css('background-color', this.checked ? '#CCC' : '#FFF')
.prop('disabled',this.checked);
}).change();
DEMO
You need to use the change event and check this.checked within the event's function.

Duplicating HTML elements and the contents within in the HTML document

Suppose I have the following code:
<div id="Car1Container">
<label id="Car1YearLabel" for="Car1Year">Year</label>
<input id="Car1Year" name="Car1Year" type="text" maxlength="4" onfocus="FieldOnFocus(this)" onkeydown="FieldOnKeyDown(this)" onkeyup="FieldOnKeyUp(this)" onblur="FieldOnBlur(this)"/>
<label id="Car1MakeLabel" for="Car1Make">Make</label>
<input id="Car1Make" name="Car1Make" type="text" maxlength="15" onfocus="FieldOnFocus(this)" onkeydown="FieldOnKeyDown(this)" onkeyup="FieldOnKeyUp(this)" onblur="FieldOnBlur(this)"/>
<label id="Car1ModelLabel" for="Car1Model">Model</label>
<input id="Car1Model" name="Car1Model" type="text" maxlength="16" onfocus="FieldOnFocus(this)" onkeydown="FieldOnKeyDown(this)" onkeyup="FieldOnKeyUp(this)" onblur="FieldOnBlur(this)"/>
<button id="AddVehicleButton1" name="AddVehicleButton1" type="button" onclick="AddVehicle()">Add Vehicle</button>
</div>
<div id="Car2Container" style = "display: none;">
<label id="Car2YearLabel" for="Car2Year">Year</label>
<input id="Car2Year" name="Car2Year" type="text" maxlength="4" onfocus="FieldOnFocus(this)" onkeydown="FieldOnKeyDown(this)" onkeyup="FieldOnKeyUp(this)" onblur="FieldOnBlur(this)"/>
<label id="Car2MakeLabel" for="Car2Make">Make</label>
<input id="Car2Make" name="Car2Make" type="text" maxlength="15" onfocus="FieldOnFocus(this)" onkeydown="FieldOnKeyDown(this)" onkeyup="FieldOnKeyUp(this)" onblur="FieldOnBlur(this)"/>
<label id="Car2ModelLabel" for="Car2Model">Model</label>
<input id="Car2Model" name="Car2Model" type="text" maxlength="16" onfocus="FieldOnFocus(this)" onkeydown="FieldOnKeyDown(this)" onkeyup="FieldOnKeyUp(this)" onblur="FieldOnBlur(this)"/>
<button id="AddVehicleButton2" name="AddVehicleButton2" type="button" onclick="AddVehicle2()">Add Vehicle</button>
</div>
Currently, AddVehicle() just changes the Car2Container style to 'block'. I have a finite number of these and I want it to be dynamic. I have some code to attempt to write it to a page, but it erases everything on the page and doesn't really work.
I want to write an AddVehicle() function to duplicate the Car1Container and place it right below in the HTML document (except all the 1s become 2s). This is turning out to be quite a challenge! Can anyone help get me moving in the right direction?
Thanks!
You can use cloneNode(true) for cloning the block, then go through childNodes property to find all the children (maybe recursively) and replace their ids and names.
Added: Here's a working example:
var container = document.getElementById('Car1Container');
var copy = container.cloneNode(true);
container.parentNode.appendChild(copy);
The jQuery Clone() will do this rather nicely. Granted, it won't increase the ID's, but I'm not convinced it needs to. Just name the fields CarYear, CarMake etc. When the values are posted to the server, if you've duplicated three of the div's, they'll be comma-separated. If necessary, you could iterate through the items and change the id's manually.
I think the jquery clone function would be useful for this.
If you want to use jquery you can just do:
var index = 1;
function copycar(){
index++;
var $tmp = $("#Car1Container").clone();
$tmp.children().each(function(){
var oldID = $("this").attr("id");
var newId = oldId.substring(0,3)+index+oldId.substring(4);
$(this).attr("id", newId);
}
$("#Car1Container").after($tmp);
}
Without using jQuery, just raw JavaScript you could use insertAdjacentHTML.
Example:
document.getElementById(‘ID’).insertAdjacentHTML(position, markup)
where position can be "beforebegin", "afterbegin", "beforeend", or "afterend"
http://lionheart.sg/insertadjacenthtml/
This should be faster than the clone method in jQuery.

Categories

Resources