Change value of disabled checkbox - javascript

So I've run across a little snag. I have a page where I have a checkbox being displayed but is disabled (the user can't change it's value due that it's DB driven). Below this checkbox, I have an autocomplete field. Should an item from the autocomplete come back, I need to be able to toggle the value of the disabled checkbox. However, I'm unable to do so at this moment.
Here is my code so far.
View
...
<tr>
<td class="adminTitle">
#Html.NopLabelFor(model => model.IsSpecialOrder):
</td>
<td class="adminData">
#Html.DisplayFor(model => model.IsSpecialOrder)
#Html.HiddenFor(model => model.IsSpecialOrder)
</td>
</tr>
<tr>
<td class="adminTitle">
#Html.NopLabelFor(model => model.ItemNumber):
</td>
<td class="adminData">
#if (Model.Id > 0)
{
#Html.DisplayFor(model => model.ItemNumber)
}
else
{
#Html.EditorFor(model => model.ItemNumber)
}
</td>
</tr>
...
<script type="text/javascript">
...
$("#ItemNumber").autocomplete({
minLength: 2,
source: function (request, response) {
var itemNumber = $("#ItemNumber").val();
//Get available Products based on search parameter and map data
$.getJSON('#Url.Action("GetProductsByItemNumber", "PurchaseOrder")', { searchProduct: itemNumber }, function (data) {
for (var i = 0; i < data.length; i++) {
productData.push({ 'Id': data[i].Id, 'Name': data[i].Name, 'ItemNumber': data[i].ItemNumber, 'Description': data[i].Description,
'IsSpecialOrder': data[i].IsSpecialOrder
});
}
response($.map(data, function (item) {
return {
value: item.ItemNumber,
id: item.Id
};
}));
})
},
select: function (event, ui) {
if (ui.item.id == 0) {
//Do some house cleaning and alert user to mistake
alert("You must retry your search for a Product");
$("#Name").val("");
$("#ItemNumber").val("");
$(".ProductDescription").html("");
document.getElementById("#Html.FieldIdFor(model => model.IsSpecialOrder)").checked = false;
//$("#IsSpecialOrder").prop("checked", false);
return false;
}
//Record ProductId
$("#ProductId").val(ui.item.id);
//Fill RequestorExt with correct data
var description = GetData(productData, ui.item.id, "desc");
var name = GetData(productData, ui.item.id, "name");
var isSpecialOrder = GetData(productData, ui.item.id, "is");
$(".ProductDescription").html(description);
$("#Name").val(name);
document.getElementById("#Html.FieldIdFor(model => model.IsSpecialOrder)").checked = isSpecialOrder;
//$("#IsSpecialOrder").prop("checked", isSpecialOrder);
}
});
...
</script>
From what I've been reading, disabled fields cannot be changed without enabling. I'm guessing that is the only way to fix this but wanted to make sure first. Any ideas?

From what I've been reading, disabled fields cannot be changed without
enabling. I'm guessing that is the only way to fix this but wanted to
make sure first. Any ideas?
Disabled fields can sure be changed see this fiddle. Double check that you have the right value in your js code.
For reference (same code that's on fiddle):
<input type="checkbox" disabled="disabled" checked="checked" id="chkbox"/>
<input type="button" value="Toggle" id="toggle"/>
var chkBox = $("#chkbox");
$("#toggle").click(function(){
if (chkBox.is(':checked')) {
chkBox.prop('checked', false);
}
else {
chkBox.prop('checked', true);
}
});

It does not matter if checkbox is enabled or disabled. You should remove checked attribute from checkbox instead of setting it's checked property to false, otherwise it will remain checked:
document.getElementById("#Html.FieldIdFor(model => model.IsSpecialOrder)").removeAttribute('checked');
Example: http://jsbin.com/izonur/2/edit

disabled items are not submited by the form http://www.w3.org/TR/html401/interact/forms.html#h-17.12
you can have readonly items that are submited with the form (exactly the opposite of what you want)
I guess you are submitting form via a javascript somehow not properly. You must EXCLUDE disabled items from form when submitting, so it will work accordingly.

Related

Onkeyup to fire a get request after only a few charcters

I am using Onkeyup to fire when a user inputs a certain ID into the search box. One problem I am trying to fix is having the function run only after 4 or more characters are in the submission box. For example, the ID number 0949 is fired when the user types out each digit, returning a GET request error each time when it should only fire at the end of the 4 digit submission. Here is a screenshot from the console log:
Ive tried including a .length to my onkeyup function as well as a fail catch to try but nothing works and it still fires after every single input. Here is my JavaScript code:
const getAssetInfo = (assetTag, index) => {
// get the table row that this input is in
$.get("http://localhost:3000/assets/" + assetTag , (data) => {
// find the `.description` element and set it's value
if (data){
$(`#manufacturer_serial_no${index}`).val(data.serial_no);
$(`#description${index}`).val(data.description);
$(`#cost${index}`).val(data.cost);
$(`#po_no${index}`).val(data.po_no);
}
console.log(data);
})
.fail(() => {
// alert("DONE");
// console.log(index);
$(`#manufacturer_serial_no${index}`).val("");
$(`#description${index}`).val("");
$(`#cost${index}`).val("");
$(`#po_no${index}`).val("");
}); };
$('document').ready(() => {
// Handler to Add New Asset
const table = $("#formTable tbody");
let count = 1;
$('#add').click(() => {
const newRow = `
<tr index="${count}">
<form>
<td><input class="asset-tag" id='asset_tag_no${count}' type='text'
onkeyup = "getAssetInfo(this.value,${count})";
bottom required /></td>
<td><input class="serial-no" id='manufacturer_serial_no${count}' type='text' bottom required readonly/></td>
<td><textarea class="description" id='description${count}' type='text' bottom required readonly description></textarea></td>
<td><input id='cost${count}' type='value' bottom require readonly/></td>
<td><input id='po_no${count}' type='text' bottom require readonly/></td>
<td><textarea id='remarks${count}' type='text' bottom remarks></textarea></td>
<td><button type="button" index="${count}" class="btn btn-danger btn-remove">X</button></td>
</form>
</tr>
`;
table.append(newRow);
// Handler to Remove New Asset
$('.btn-remove').click(function(){
let index = $(this).attr('index');
$(`tr[index='${index}'`).remove();
});
count++;
});
What is the most optimal way to ensure that only 4 or more digits can be entered into the search box, before it sends a GET request?
You should be able to wrap your getAssetInfo function with an if statement checking the amount of characters in the searchbar. Try rewriting the getAssetInfo function like this:
const getAssetInfo = (assetTag, index) => {
if (assetTag.length >= 4){
// get the table row that this input is in
$.get("http://localhost:3000/assets/" + assetTag , (data) => {
// find the `.description` element and set it's value
if (data){
$(`#manufacturer_serial_no${index}`).val(data.serial_no);
$(`#description${index}`).val(data.description);
$(`#cost${index}`).val(data.cost);
$(`#po_no${index}`).val(data.po_no);
}
console.log(data);
})
.fail(() => {
// alert("DONE");
// console.log(index);
$(`#manufacturer_serial_no${index}`).val("");
$(`#description${index}`).val("");
$(`#cost${index}`).val("");
$(`#po_no${index}`).val("");
});
} else {
console.log('not enough characters to call API endpoint');
}
};
In this if statement, I'm checking if the search bar has 4 or more characters before making the API call.

clicking through saved checkbox states

The below works to save the states of my checkboxes, then sets the items saved back to checked when called in my load__() function; however I need to instead of just setting to checked, I need to actually have them .click() through in my load__() function as the data is not being served otherwise.
function checkSaver() {
user = JSON.parse(localStorage.getItem(user));
var inputs = document.querySelectorAll('input[type="checkbox"]');
user.userAchkData = [];
inputs.forEach(function(input){
user.userAchkData.push({ id: input.id, checked: input.checked });
});
localStorage.setItem(username, JSON.stringify(user));
console.log(JSON.stringify(user));
}
function load_() {
// get saved latest checkbox states, recheck
user = JSON.parse(localStorage.getItem(user));
var inputs = user.userAchkData;
inputs.forEach(function(input){
if (input.id) {
// I need to click through the found checked here
document.getElementById(input.id).checked = input.checked;
}
});
You can check if they're checked and then programmatically trigger a click:
if (input.id) {
// I need to click through the found checked here
const element = document.getElementById(input.id);
element.checked = input.checked;
if (input.checked) element.click();
}
I fiddled around a bit and got to a simple working example for checking saved checkboxes. Maybe you can adapt this to your needs:
const container = document.getElementById('checkboxes');
const data = JSON.parse(localStorage.getItem('checkboxes')) || new Array(3).fill(false);
window.addEventListener('DOMContentLoaded', () => {
[...container.children].forEach((child, i) => { child.checked = data[i]; });
});
container.onchange = ({ target }) => {
data[target.dataset.id] = target.checked;
localStorage.setItem('checkboxes', JSON.stringify(data));
};
<div id="checkboxes">
<input type="checkbox" data-id="0">
<input type="checkbox" data-id="1">
<input type="checkbox" data-id="2">
</div>

Autocomplete is not working after Postback in mvc

In my mvc application i'm appending jquery autocomplete to the searchbox. my problem is at first time autocomplete is working fine. it shows the related items when ever we type in the searchbox. after selecting one of the item it will redirect to another page. where the searchbox autocomplete is not working.
Here is my code:
View:
<div id="targetDiv">
#Html.TextBox("name", null, new { id = "SearchBox", #class = "SearchBox" })
</div>
Javascript code:
<script type="text/javascript">
function load() {
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(getItems);
}
$(document).ready(function () {
//We have used keyup event to track the user enter value in the textbox.
$("#SearchBox").keyup(function () {
//Fetching the textbox value.
var query = $(this).val();
//Calling GetItems method.
getItems(query);
});
function getItems(query) {
//var path = '#Url.Action("Suggest", "Home")';
//Here we are using ajax get method to fetch data from the list based on the user entered value in the textbox.
//We are sending query i.e textbox as data.
$.ajax({
url: '#Url.Action( "RemoteData", "Home")',
data: { "query": query },
type: 'POST',
dataType: 'json',
success: function (response) {
if (response.Data != null) {
if ($("#targetUL") != undefined) {
//If the UL element is not null or undefined we are clearing it, so that the result is appended in new UL every next time.
$("#targetUL").remove();
}
//assigning json response data to local variable. It is basically list of values.
data = response.Data;
//appending an UL element to show the values.
$("#targetDiv").append($("<ul id='targetUL'></ul>"));
//Removing previously added li elements to the list.
$("#targetUL").find("li").remove();
//We are iterating over the list returned by the json and for each element we are creating a li element and appending the li element to ul element.
$.each(data, function (i, value) {
//On click of li element we are calling a method.
$("#targetUL").append($("<li class='targetLI' onclick='javascript:appendTextToTextBox(this)'>" + value + "</li>"));
});
}
else {
//If data is null the we are removing the li and ul elements.
$("#targetUL").find("li").remove();
$("#targetUL").remove();
}
},
error: function (xhr, status, error) {
}
});
}
});
//This method appends the text oc clicked li element to textbox.
function appendTextToTextBox(e) {
//Getting the text of selected li element.
var textToappend = e.innerText;
//setting the value attribute of textbox with selected li element.
$("#SearchBox").val(textToappend);
//Removing the ul element once selected element is set to textbox.
$("#targetUL").remove();
}
</script>
controller code:
[HttpPost]
public ActionResult RemoteData(string query)
{
ArrayList list = new ArrayList();
SearchModel searchmodel = new SearchModel();
DataTable dt = new DataTable();
dt = searchmodel.FilteredSearchProductDisplay(query, 5, 0);
if (dt.Rows.Count > 0)
{
foreach (DataRow dr in dt.Rows)
{
list.Add(dr["ProductName"]);
}
}
return Json(new { Data = list });
}
Redirected-Page:
if (#Model.dtProduct.Rows.Count > 0)
{
<div style="width:100%; height:auto;">#Html.Raw(#Model.dtProduct.Rows[0]["ThumbnailFilename"])</div>
<br />
if (ViewBag.RedirectedFromPage == "Search" || ViewBag.RedirectedFromPage == "OfferProduct")
{
if (#Model.dtProduct.Rows[0]["Stock"].ToString().Length > 0)
{
<table id ="priceTable">
<tr>
#if(#offerPrice > 0)
{
<td style="width:10%" class="divSizehPrice"><label>#Html.Raw(#Model.dtcurrentCurrency.Rows[0]["HTMLENTITY"])#APrice.ToString("0.00")</label></td>
<td style="width:90%" class="divSizehPrice"><label>RRP </label><p>#Html.Raw(#Model.dtcurrentCurrency.Rows[0]["HTMLENTITY"])#Price.ToString("0.00")</p></td>
}
else
{
<td colspan=2 style="width:90%" class="divSizehPrice"><p>#Html.Raw(#Model.dtcurrentCurrency.Rows[0]["HTMLENTITY"])#APrice.ToString("0.00")</p></td>
}
</tr>
</table>
<div id="divPrice2"style="display:none">
<table>
<tr>
<td>#Html.Raw(#Model.dtcurrentCurrency.Rows[0]["HTMLENTITY"])</td>
<td><div id="PriceDiv2"></div></td>
</tr>
</table>
</div>
<br />
Change currency
<br />
Add to Shopping Cart
}
else
{
using (Html.BeginForm("SelectedProductDisplay", "Product", FormMethod.Post, new { ProductId = #Model.dtProduct.Rows[0]["ProductId"], ProductpriceId = #Model.dtProduct.Rows[0]["ProductPriceId"] }))
{
<b>Out of stock</b>
<br />
#*<p>Please enter your email address below and we will contact you when it comes back in to stock.</p>
<br />
<label>Email:</label> #Html.TextBoxFor(m => m.OutOfStockEmail, new { id = "emailid" })
<br />
<div id="erroremail" class="validationColor" style="width:100%; text-align:center"></div>
<label>#Model.OutOfStockStatus</label>
<input type="submit" value="Notify Me" onclick="return checkEmail()"/>*#
}
Continue Shopping
}
<br />
<div class="divSearchHeader">
<p>#Html.Raw(Model.dtProduct.Rows[0]["ProductName"])</p>
<br />
</div>
<div class="divSearchContent">
#Html.Raw(#Model.dtProduct.Rows[0]["ProductDescription"])
</div>
<div class="divSearchContent">
#Html.Raw(#Model.dtProduct.Rows[0]["Description"])
</div>
}
else
{
<table style="width:100%" id="priceTable1">
#if (offerPrice > 0)
{
<tr>
<td style="width:25%"><div class="divSizehPrice">#APrice.ToString("0.00")</div></td>
<td style="width:75%"><div class="divSizehPrice"><p><label>RRP </label>#Price.ToString("0.00")</p></div></td>
</tr>
}
else
{
<tr>
<td colspan=2 class="divSizehPrice"><p>#Html.Raw(#Model.dtcurrentCurrency.Rows[0]["HTMLENTITY"])#APrice.ToString("0.00")</p></td>
</tr>
}
</table>
<div id="divPrice1"style="display:none" class="divSizehPrice">
<table>
<tr>
<td>#Html.Raw(#Model.dtcurrentCurrency.Rows[0]["HTMLENTITY"])</td>
<td><div id="PriceDiv1"></div></td>
</tr>
</table>
</div>
<br />
Change currency
<br />
Add to Shopping Cart
<br />
<div class="divSearchHeader">
<p>#Html.Raw(Model.dtProduct.Rows[0]["Name"])</p>
<br />
</div>
<div class="divSearchContent">
#Html.Raw(#Model.dtProduct.Rows[0]["Description"])
</div>
}
}
else
{
<p>No records found.</p>
}
Please use live instead simple keyup:
$('selector').live('keyup',function(){
//your code
});
Try :
$('sel').on('keyup',function(){
//your code
});
Please try this
$("body").delegate("selector","keyup",function(e){//your code.})
Try this:
$('selector').on('input', function(){
// Do your stuff here
});
Check the 'input' event,
I have also used Jquery AutoComplete Search Box it is working fine the only difference is in Controller Code
public ActionResult Autocomplete(string term)
{
// Return the Result list store in searchResultList
return Json(searchResultList, JsonRequestBehavior.AllowGet);
}
Removed Httpost Attribute
While Returning Json, use the 2nd Overload Method JsonRequestBehavior.AllowGet
Hope it helps you, Please note I am using MVC4 VS 2010

Form validation linking fields as required

I am looking to do some client size validation. Below you will find an example of my template.
When this form is submitted it is okay for a line to be empty. However I want to be sure if even one item in a line is selected/has an entry that all lines will have an entry. For example. There should always be either Nothing OR require a Date, start Time, stop time, and class. (the class is populated by a button in another location) The validation will be used to warn the individual if they are missing anything and if they submit we will disregard the record as incomplete.
I have looked at jquery Validation as we are already using it on other forms in our project but, I have been unable to find a way to link row items together.
<form>
<table id="payableEventTable" class="table table-condensed table-striped">
<thead>
<tr>
<th>Date</th>
<th>Class/Scenario</th>
<th>Start</th>
<th>Stop</th>
<th>Break</th>
</tr>
</thead>
<tbody id="payableEventTableBody">
<c:forEach begin="0" end="5" varStatus="i">
<tr>
<td><input type="date" class="input-small" name="claimForm.payableEvents[${i.index}].eventDate" /></td>
<td>
<select class="classSelect" name="claimForm.payableEvents[${i.index}].event">
<option></option>
</select>
</td>
<td><input type="text" class="input-small" name="claimForm.payableEvents[${i.index}].eventStartTime" /></td>
<td><input type="text" class="input-small" name="claimForm.payableEvents[${i.index}].eventStopTime" /></td>
<td>
<select>
<option value="0" selected>No Break taken</option>
<option value="15">15 Minutes</option>
<option value="30">30 Minutes</option>
<option value="45">45 Minutes</option>
</select>
</td>
</tr>
</c:forEach>
</tbody>
</table>
</form>
Technology we are willing to use. HTML, CSS, javaScript, jQuery, (lightweight plugins for jquery). We also have to make sure the solution works back to IE8.
Edit:
I built a JSFiddle. To help with visualization.
Edit:
I have come up with an answer. However, if anyone is able to improve on my answer, streamline it/make it look nicer I would still be willing to give out the Bounty to that person.
Here is my suggestion: To make your code more legible, you can combine the three functions validateRow(), isRowEmpty(), isRowComplete() into one simpler validateRow() function. Also it is a lot faster, because you only need to go through all elements and check their values once instead of twice.
I also created a simple to use validateForm() function to tidy things up.
The validateForm() function can now be used in an event handler:
// Event Handler
$('#validate').bind('click', function(e){
e.preventDefault();
if(validateForm()) {
alert("next");
//$('#claimWizard').wizard('next');
}
});
// Form Validation
var validateForm = function(){
var valid = true;
$('#payableEventTableBody tr').each(function() {
if (validateRow($(this))) {
$(this).removeClass("error");
}
else {
valid = false;
$(this).addClass('error');
}
});
return valid;
}
var validateRow = function(row){
var state = null,
valid = true;
row.find('input, select').each(function() {
var value = $(this).val(),
isEmpty = (value != 0 && value !== '');
//if its the first element just save the state
if(state === null) {
state = isEmpty;
}
// if this field has not the same state as the rest
else if(state !== isEmpty) {
valid = false;
}
})
return valid;
}
And here's your fiddle with my code implemented: http://jsfiddle.net/KNDLF/
So, what I came up with:
Three methods: isRowValid(), isRowEmpty(), isRowComplete()
The rows need to be either empty or complete.
//The following code is part of my logic on continuing
var valid = true;
$('#payableEventTableBody tr').each(function() {
$(this).removeClass('error');
if (!isRowValid($(this))) {
valid = false;
$(this).addClass('error');
return;
}
});
if (valid) {
$('#claimWizard').wizard('next');
}
//The following is my validation methods
<script type="text/javascript">
function isRowValid($tr) {
return (isRowEmpty($tr) || isRowComplete($tr));
}
function isRowEmpty($tr) {
var isEmpty = true;
$tr.find('input, select').each(function() {
var value = $(this).val();
if (value != 0 && value !== '') {
isEmpty = false;
}
});
return isEmpty;
}
function isRowComplete($tr) {
var isComplete = true;
$tr.find('input, select').each(function(){
var value = $(this).val();
if(value === ''){
isComplete = false;
}
});
return isComplete;
}
</script>
This should be good to start with
http://jsfiddle.net/rJaPR/
$('#validate').bind('click', function(e){
e.preventDefault();
$('#payableEventTable tr').each(function(){
var tr = $(this);
var newRowValue=0;
$(tr).find('input, select').each(function(){
var value = $(this).val();
switch(newRowValue){
case 0:
// first input/select
newRowValue = ((value!=0 && value!='') ? 1 : -1);
break;
case 1:
// there are some values in this row
if (value==0 || value=='')
tr.css('backgroundColor', 'red');
break;
case -1:
// this row should be empty
if (value!=0 && value!='')
tr.css('backgroundColor', 'red');
break;
}
})
})
})

Using javascript in a view to enable textbox on radiobutton state for each items in a list

I have this view with 2 radiobuttons strongly-typed to a model, and I wish to enable / disable textbox fields depending on the state of those radiobuttons.
Here is the view and the script I've been working on right now:
#model IList<MyApp.Models.ObjInfo>
#{
ViewBag.Title = "SendItems";
}
<h2>Ebay Items</h2>
<script src="/Scripts/jquery-1.7.1.min.js"
type="text/javascript"></script>
<script type="text/javascript">
function dostate1() {
$("#textfield1").attr("disabled", "disabled");
$("#textfield2").removeAttr("disabled");
$("#textfield3").removeAttr("disabled");
}
function dostate2() {
$("#textfield1").removeAttr("disabled");
$("#textfield2").attr("disabled", "disabled");
$("#textfield3").attr("disabled", "disabled");
}
$(document).ready(function ()
{
alert("The document is ready");
if ($("#state1").is(":checked")) {
dostate1();
} else {
dostate2();
}
$("#state1").click(function (){
alert("Auction radio button has been clicked");
dostate1();
});
$("#state2").click(function () {
alert("Buy It Now radio button has been clicked");
dostate2();
});
});
</script>
<p>
#using (Html.BeginForm("ManageItems", "Item Inventory"))
{
(...)
#for (int i = 0; i < Model.Count; i++)
{
<p>
<tr>
<td>#Html.DisplayFor(x => x[i].m_OtrObj.m_ObjName)</td>
<td>#Html.RadioButtonFor(x => x[i].m_State, "State 1", new {id = "state1", style ="width: 50px"})</td>
<td>#Html.RadioButtonFor(x => x[i].m_State, "State 2", new {id = "state2", style ="width: 50px"})</td>
<td>
#Html.TextBoxFor(x => x[i].m_Field1, new{id = "textField1", style = "width:200px"})
</td>
<td>
#Html.TextBoxFor(x => x[i].m_Field2, new {id = "textField2", style = "width:200px"})
</td>
<td>
#Html.TextBoxFor(x => x[i].m_Field3, new {id ="textField3", style = "width:200px" })
</td>
</tr>
</p>
}
</table>
<input type="submit" value="Do Something"/>
}
</p>
Right now I have 2 main problems:
Clicking on each radiobutton actually disable the fields I wish to have disabled, but do not activate the other fields;
The script actually runs only when a button is clicked, but should run at start to avoid field 1 being active since by default the "state 1" radio button is enabled.
I'm REALLY a newbie as to javascript, so can anyone help me out? Thanks!!
EDIT **
I've modified the script to show you the evolution so far, thanks to everyone who helped out, the script works, but only for the first item in the list. Taking into account that it's a list of object (see #model), how can I affect each items in the list individually?
Change your script to
$(document).ready(function ()
{
alert("The document is ready");
$("#state1").change(function (){ // use change event instead of click
alert("state1 radio button has been changed");
// use prop instead of attr and always use the disabled attribute
// (there is not enabled). Use true/false to alter its state
$("#textField1").prop("disabled", true);
$("#textField2").prop("disabled", false);
$("#textField3").prop("disabled", false);
}).trigger('change'); // trigger a change event since it is the default
$("#state2").change(function() { // use change event instead of click
alert("state2 radio button has been changed");
$("#textField1").prop("disabled", false);
$("#textField2").prop("disabled", true);
$("#textField3").prop("disabled", true);
});
});
Ok, so:
you need to enable the radio buttons by using jQuery's removeAttr function (http://api.jquery.com/removeAttr/):
alert("state1 radio button has been clicked");
$("#textField1").attr("disabled", "disabled");
$("#textField2").removeAttr("disabled");
$("#textField3").removeAttr("disabled");
this is because it's the presence of the "disabled" attribute that disables controls.
if you break your enable/disable code out into functions:
function doState1() {
$("#textField1").attr("disabled", "disabled");
$("#textField2").removeAttr("disabled");
$("#textField3").removeAttr("disabled");
}
function doState2() {
$("#textField1").removeAttr("disabled");
$("#textField2").attr("disabled", "disabled");
$("#textField3").attr("disabled", "disabled");
}
$(document).ready(function () {
doState1();
$("#state1").change(function (){
doState1();
});
$("#state2").change(function() {
doState2();
});
});
you can then call them when the doc is ready, and hook them into the click actions.
Edit
To repeat this for sets of buttons + fields, I would have your loop generate ids that are unique to each element, e.g.
<input type="radio" id="state_1_1">State 1_1
<input type="radio" id="state_2_1">State 2_1
<input type="text" id="textField_1_1">Text 1_1
<input type="text" id="textField_2_1">Text 2_1
<input type="text" id="textField_3_1">Text 3_1
<input type="radio" id="state_1_2">State 1_2
<input type="radio" id="state_2_2">State 2_2
<input type="text" id="textField_1_2">Text 1_2
<input type="text" id="textField_2_2">Text 2_2
<input type="text" id="textField_3_2">Text 3_2
and then change the code to use a "search start of id" selector and split the id to obtain the set and state/text field number:
function doState1(theid) {
var idarr = theid.split("_");
var state = idarr[1];
var idval = idarr[2];
$("#textField_1_" + idval).attr("disabled", "disabled");
$("#textField_2_" + idval).removeAttr("disabled");
$("#textField_3_" + idval).removeAttr("disabled");
}
function doState2(theid) {
var idarr = theid.split("_");
var state = idarr[1];
var idval = idarr[2];
$("#textField_1_" + idval).removeAttr("disabled");
$("#textField_2_" + idval).attr("disabled", "disabled");
$("#textField_3_" + idval).attr("disabled", "disabled");
}
$(document).ready(function () {
if ($("#state_1_1").is(":checked")) {
doState1("state_1_1");
} else {
doState2("state_2_1");
}
$('input[id^="state_1_"]').change(function () {
doState1(this.id);
});
$('input[id^="state_2_"]').change(function () {
doState2(this.id);
});
});
See http://jsfiddle.net/raad/4vHBv/17/
First , You have to understand the there is no such attribute by the name of 'enable'. For enable the html element , you have to remove the disabled attribute from fields.
If you want to change your field from disabled to enable state , then just do as i am writing:
$("#textField2").removeAttr("disabled");
$("#textField3").removeAttr("disabled");
Above code will enable the the Textbox with id "#textField2" and "#textField3"
Your first question is already answered above. As for the second one I would suggest moving the state checking to a function like this:
function checkState(){
if($('#state1').is(':checked')){
//do stuff...
}
}
And then run the function once on document ready and every time the state of the radio buttons is changed.

Categories

Resources