I have a table with three columns and multiple rows. 2nd and third column consist of a textbox(first child of a container) and a checkbox respectively.
Textbox
<td class="SBS1 c4">
<input class="Medium InputText" type="text" name="QR~QID33#1~1~1~TEXT" id="QR~QID33#1~1~1~TEXT" value="" disabled="">
<label class="offScreen" for="QR~QID33#1~1~1~TEXT"> - - hh</label>
</td>
Checkbox
<td class="SBS2 c7">
<input type="checkbox" id="QR~QID33#2~1~1" name="QR~QID33#2~1~1" value="Selected">
<label class="q-checkbox q-checked" for="QR~QID33#2~1~1"></label>
<label class="offScreen" for="QR~QID33#2~1~1"> - ó †ºrandom text</label>
</td>
I have to disable and enable the textboxes in each row on checkbox check and uncheck respectively using javascript. but there seem to be some pagelifecycle issues with the script I am using. Here is the Javascript that I am using in my Qualtrics survey JS interface,
Qualtrics.SurveyEngine.addOnload(function()
{
/*Place Your JavaScript Here*/
var count=document.getElementsByClassName("q-checkbox").length;
for(var i=0;i<count;i++)
{
document.getElementsByClassName("q-checkbox")[i].parentNode.addEventListener("click",hideFunc);
}
function hideFunc()
{
console.log(this.className);
if(this.classList.contains("checkers"))
{
//this.classList.toggle("checkers");
this.previousSibling.previousSibling.previousSibling.firstChild.disabled="false";
this.classList.add("checkers");
return;
}
else
if(!(this.classList.contains("checkers")))
{
this.previousSibling.previousSibling.previousSibling.firstChild.disabled="true";
this.classList.remove("checkers");
return;
}
}
});
I am just trying to toggle or add/remove the class "checkers"and setting "disabled" property of the texboxes accordingly. The code above in HideFunc is one of the work-around I have tried but it is not working.
Is there another way to check for checkbox change?
As the first comment hinted, a better approach is to check the status of the checkbox rather than add/remove a class. Also, making use of prototypejs makes it easier. Try this:
Qualtrics.SurveyEngine.addOnload(function() {
var qid = this.questionId;
$(qid).select('tr.Choice').each(function(choice,idx) { //loop through each row
var cbox = choice.select('td.SBS2').first().down(); //cbox enables 1st question in row
var txtEl = choice.select('td.SBS1').first().down(); //text input to be enabled/disabled
if(cbox.checked == false) { //initialize text input disabled status
txtEl.value = null; //blank text input
txtEl.disabled = true; //disable text input
}
cbox.on('click', function(event, element) { //enable/disable text input on cbox click
if(cbox.checked == false) { //unchecked
txtEl.value = null; //blank text input
txtEl.disabled = true; //disable text input
}
else { //checked
txtEl.disabled = false; //enable text input
}
}); //end on function
}); //end row loop
});
This is another solution I could come up with ,apart from the correct solution by T. Gibbons
var $j= jQuery.noConflict();
$j("td.SBS2 ").click(function(){
$j(this).closest("tr").find(".InputText").prop("disabled",$j(this).children("input")[0].checked);
$j(this).closest("tr").find(".InputText").prop("value","");
var len=document.getElementsByClassName("InputText").length;
for(var i=0;i<=len;i++)
{
document.getElementsByClassName("InputText")[i].style.width="300px";
}
});
Related
I'm trying to change the color of my checkbox text label when the user checks the box and clicks the toggle button. I looked up other examples and tried to make my own solution below but it doesn't work when I check the boxes I want to check and click the button. I was wondering why?
function addItem() {
var input = document.getElementById("textbox");
var wrapper = document.getElementById("checklist_items");
if (input.value.trim() != "") {
var new_element = document.createElement("DIV");
new_element.innerHTML = '<input type="checkbox"> ' + input.value;
wrapper.appendChild(new_element);
document.getElementById('textbox').value = '';
} else {
alert("You must enter at least 1 character.");
}
}
function toggleItem() {
var chkbx = document.querySelectorAll('checklist_items');
if (chkbx.checked) {
document.getElementById('checklist_items').style.color = "red";
} else {
document.getElementById("checklist_items").style.backgroundColor = "transparent";
}
}
<html>
<head>
<title>Checklist</title>
</head>
<body>
<div><h1>My to-do list</h1></div><br />
<div id ="myCheckList">Enter an item:</div>
<div>Type something: <input type="text" id="textbox"></input></div>
<input type="button" id="addBut" value = "Add item" onclick="addItem()"/>
<input type="button" id="toggleBut" value = "Toggle highlight" onclick="toggleItem()"/>
<script src="addHandler.js"></script>
<div id="checklist_items"></div>
</body>
</html>
How my program works is the user enters a bunch of text in the textbox and clicks the add button, which creates a checkbox for their input. I want the name of their input beside the checkbox to change colors when I check it and click the toggle button.
var chkbx = document.querySelectorAll('checklist_items') needs to be var chkbx = document.querySelectorAll('#checklist_items') or var chkbx = document.getElementById('checklist_items').
querySelectorAll takes CSS selectors as arguments, which are either html elements or class or id names with the corresponding prefix. IDs have the prefix # and classes have the prefix .
Using JQuery:
$(".your_checkbox_class").change(function () {
if ($(this).is(':checked')) {
$(this).css("background-color","your_color_here");
}
};
EDIT:
You should also give this checkbox class or id
EDIT 2:
document.getElementById('checklist_items').style.color = "red";
means that font color will change but checkbox has no text
I'm new at Javascript and I'm trying to reveal additional info only if any 2 out of 3 checkboxes are checked.
Here is my code so far (I'm trying to enter my code in the question but It's not working, sorry. I also may have made it more complicated then necessary, sorry again). I did place my code in the Demo.
<script>
var checkboxes;
window.addEvent('domready', function() {
var i, checkbox, textarea, div, textbox;
checkboxes = {};
// link the checkboxes and textarea ids here
checkboxes['checkbox_1'] = 'textarea_1';
checkboxes['checkbox_2'] = 'textarea_2';
checkboxes['checkbox_3'] = 'textarea_3';
for ( i in checkboxes ) {
checkbox = $(i);
textbox = $(checkboxes[i]);
div = $(textbox.id + '_container_div');
div.dissolve();
showHide(i);
addEventToCheckbox(checkbox);
}
function addEventToCheckbox(checkbox) {
checkbox.addEvent('click', function(event) {
showHide(event.target.id);
});
}
});
function showHide(id) {
var checkbox, textarea, div;
if(typeof id == 'undefined') {
return;
}
checkbox = $(id);
textarea = checkboxes[id];
div = $(textarea + '_container_div');
textarea = $(textarea);
if(checkbox.checked) {
div.setStyle('display', 'block');
//div.reveal();
div.setStyle('display', 'block');
textarea.disabled = false;
} else {
div.setStyle('display', 'none');
//div.dissolve();
textarea.value = '';
textarea.disabled = true;
}
}
<label for="choice-positive">
<script type="text/javascript">
function validate(f){
f = f.elements;
for (var c = 0, i = f.length - 1; i > -1; --i)
if (f[i].name && /^colors\[\d+\]$/.test(f[i].name) && f[i].checked) ++c;
return c <= 1;
};
</script>
<label>
<h4><div style="text-align: left"><font color="black">
<input type="checkbox" name="colors[2]" value="address" id="address">Full Address
<br>
<label>
<input type="checkbox" name="colors[3]" value="phone" id="phone">Phone Number <br>
<label>
<input type="checkbox" name="colors[4]" value="account" id="account">Account Number <br>
</form>
<div class="reveal-if-active">
<h2><p style = "text-decoration:underline;"><font color="green">Receive the 2 following
pieces of info:</h2></p>
</style>
Sorry i wasn't able to exactly use the code you provided but tried to change just enough to get it working.
I've uploaded a possible solution to JSFiddle - you essentially can add event listeners to the checkboxes that recheck when clicked how many are selected and show/hide via removing/adding a class e.g. additionalContactBox.classList.remove('reveal-if-active');
I have a form with multiple checkboxes and I want to use JavaScript to make sure at least one is checked. This is what I have right now but no matter what is chosen an alert pops up.
JS (wrong)
function valthis(){
if (document.FC.c1.checked) {
alert ("thank you for checking a checkbox")
} else {
alert ("please check a checkbox")
}
}
HTML
<p>Please select at least one Checkbox</p>
<br>
<br>
<form name = "FC">
<input type = "checkbox" name = "c1" value = "c1"/> C1
<br>
<input type = "checkbox" name = "c1" value = "c2"/> C2
<br>
<input type = "checkbox" name = "c1" value = "c3"/> C3
<br>
<input type = "checkbox" name = "c1" value = "c4"/> C4
<br>
</form>
<br>
<br>
<input type = "button" value = "Edit and Report" onClick = "valthisform();">
So what I ended up doing in JS was this:
function valthisform(){
var chkd = document.FC.c1.checked || document.FC.c2.checked||document.FC.c3.checked|| document.FC.c4.checked
if (chkd == true){
} else {
alert ("please check a checkbox")
}
}
I decided to drop the "Thank you" part to fit in with the rest of the assignment. Thank you so much, every ones advice really helped out.
You should avoid having two checkboxes with the same name if you plan to reference them like document.FC.c1. If you have multiple checkboxes named c1 how will the browser know which you are referring to?
Here's a non-jQuery solution to check if any checkboxes on the page are checked.
var checkboxes = document.querySelectorAll('input[type="checkbox"]');
var checkedOne = Array.prototype.slice.call(checkboxes).some(x => x.checked);
You need the Array.prototype.slice.call part to convert the NodeList returned by document.querySelectorAll into an array that you can call some on.
This should work:
function valthisform()
{
var checkboxs=document.getElementsByName("c1");
var okay=false;
for(var i=0,l=checkboxs.length;i<l;i++)
{
if(checkboxs[i].checked)
{
okay=true;
break;
}
}
if(okay)alert("Thank you for checking a checkbox");
else alert("Please check a checkbox");
}
If you have a question about the code, just comment.
I use l=checkboxs.length to improve the performance. See http://www.erichynds.com/javascript/javascript-loop-performance-caching-the-length-property-of-an-array/
I would opt for a more functional approach. Since ES6 we have been given such nice tools to solve our problems, so why not use them.
Let's begin with giving the checkboxes a class so we can round them up very nicely.
I prefer to use a class instead of input[type="checkbox"] because now the solution is more generic and can be used also when you have more groups of checkboxes in your document.
HTML
<input type="checkbox" class="checkbox" value=ck1 /> ck1<br />
<input type="checkbox" class="checkbox" value=ck2 /> ck2<br />
JavaScript
function atLeastOneCheckboxIsChecked(){
const checkboxes = Array.from(document.querySelectorAll(".checkbox"));
return checkboxes.reduce((acc, curr) => acc || curr.checked, false);
}
When called, the function will return false if no checkbox has been checked and true if one or both is.
It works as follows, the reducer function has two arguments, the accumulator (acc) and the current value (curr). For every iteration over the array, the reducer will return true if either the accumulator or the current value is true.
the return value of the previous iteration is the accumulator of the current iteration, therefore, if it ever is true, it will stay true until the end.
Check this.
You can't access form inputs via their name. Use document.getElements methods instead.
Vanilla JS:
var checkboxes = document.getElementsByClassName('activityCheckbox'); // puts all your checkboxes in a variable
function activitiesReset() {
var checkboxesChecked = function () { // if a checkbox is checked, function ends and returns true. If all checkboxes have been iterated through (which means they are all unchecked), returns false.
for (var i = 0; i < checkboxes.length; i++) {
if (checkboxes[i].checked) {
return true;
}
}
return false;
}
error[2].style.display = 'none'; // an array item specific to my project - it's a red label which says 'Please check a checkbox!'. Here its display is set to none, so the initial non-error label is visible instead.
if (submitCounter > 0 && checkboxesChecked() === false) { // if a form submit has been attempted, and if all checkboxes are unchecked
error[2].style.display = 'block'; // red error label is now visible.
}
}
for (var i=0; i<checkboxes.length; i++) { // whenever a checkbox is checked or unchecked, activitiesReset runs.
checkboxes[i].addEventListener('change', activitiesReset);
}
Explanation:
Once a form submit has been attempted, this will update your checkbox section's label to notify the user to check a checkbox if he/she hasn't yet. If no checkboxes are checked, a hidden 'error' label is revealed prompting the user to 'Please check a checkbox!'. If the user checks at least one checkbox, the red label is instantaneously hidden again, revealing the original label. If the user again un-checks all checkboxes, the red label returns in real-time. This is made possible by JavaScript's onchange event (written as .addEventListener('change', function(){});
You can check that atleast one checkbox is checked or not using this simple code. You can also drop your message.
Reference Link
<label class="control-label col-sm-4">Check Box 2</label>
<input type="checkbox" name="checkbox2" id="checkbox2" value=ck1 /> ck1<br />
<input type="checkbox" name="checkbox2" id="checkbox2" value=ck2 /> ck2<br />
<script>
function checkFormData() {
if (!$('input[name=checkbox2]:checked').length > 0) {
document.getElementById("errMessage").innerHTML = "Check Box 2 can not be null";
return false;
}
alert("Success");
return true;
}
</script>
< script type = "text/javascript" src = "js/jquery-1.6.4.min.js" > < / script >
< script type = "text/javascript" >
function checkSelectedAtleastOne(clsName) {
if (selectedValue == "select")
return false;
var i = 0;
$("." + clsName).each(function () {
if ($(this).is(':checked')) {
i = 1;
}
});
if (i == 0) {
alert("Please select atleast one users");
return false;
} else if (i == 1) {
return true;
}
return true;
}
$(document).ready(function () {
$('#chkSearchAll').click(function () {
var checked = $(this).is(':checked');
$('.clsChkSearch').each(function () {
var checkBox = $(this);
if (checked) {
checkBox.prop('checked', true);
} else {
checkBox.prop('checked', false);
}
});
});
//for select and deselect 'select all' check box when clicking individual check boxes
$(".clsChkSearch").click(function () {
var i = 0;
$(".clsChkSearch").each(function () {
if ($(this).is(':checked')) {}
else {
i = 1; //unchecked
}
});
if (i == 0) {
$("#chkSearchAll").attr("checked", true)
} else if (i == 1) {
$("#chkSearchAll").attr("checked", false)
}
});
});
< / script >
Prevent user from deselecting last checked checkbox.
jQuery (original answer).
$('input[type="checkbox"][name="chkBx"]').on('change',function(){
var getArrVal = $('input[type="checkbox"][name="chkBx"]:checked').map(function(){
return this.value;
}).toArray();
if(getArrVal.length){
//execute the code
$('#msg').html(getArrVal.toString());
} else {
$(this).prop("checked",true);
$('#msg').html("At least one value must be checked!");
return false;
}
});
UPDATED ANSWER 2019-05-31
Plain JS
let i,
el = document.querySelectorAll('input[type="checkbox"][name="chkBx"]'),
msg = document.getElementById('msg'),
onChange = function(ev){
ev.preventDefault();
let _this = this,
arrVal = Array.prototype.slice.call(
document.querySelectorAll('input[type="checkbox"][name="chkBx"]:checked'))
.map(function(cur){return cur.value});
if(arrVal.length){
msg.innerHTML = JSON.stringify(arrVal);
} else {
_this.checked=true;
msg.innerHTML = "At least one value must be checked!";
}
};
for(i=el.length;i--;){el[i].addEventListener('change',onChange,false);}
<label><input type="checkbox" name="chkBx" value="value1" checked> Value1</label>
<label><input type="checkbox" name="chkBx" value="value2"> Value2</label>
<label><input type="checkbox" name="chkBx" value="value3"> Value3</label>
<div id="msg"></div>
$('input:checkbox[type=checkbox]').on('change',function(){
if($('input:checkbox[type=checkbox]').is(":checked") == true){
$('.removedisable').removeClass('disabled');
}else{
$('.removedisable').addClass('disabled');
});
if(($("#checkboxid1").is(":checked")) || ($("#checkboxid2").is(":checked"))
|| ($("#checkboxid3").is(":checked"))) {
//Your Code here
}
You can use this code to verify that checkbox is checked at least one.
Thanks!!
<tr>
<td class="value" style="width:40%;">
<label class="label">Gender value</label>
</td>
<td class="value" style="width:40%;">
<input id="checkbox" type="checkbox" tabindex="0" name="chkCustom">
<label>M</label>
<input id="checkbox" type="checkbox" tabindex="0" name="chkCustom">
<label>F</label>
<input id="checkbox" type="checkbox" tabindex="0" name="chkCustom">
<label>U</label>
</td>
</tr>
I have the above HTML, I am reading all the controls from my webpage dynamically. In above I want to read the label value to its specified type and read the next value on the basis of its type:
Please look on my code:
// Read labels text
$("#tblCustomFields tr .label").each(function () {
var value = this.innerHTML;
console.log(this);
var type = $(this).closest('td').next().find('input').val();
alert(value);
alert(type);
//If next element type is *checkbox* then read checkbox values
if(type == "checkbox")
{
// Read checkbox values
$('tblCustomFields tr input:checked').each(function (s) {
var inputCheckBox = new Array();
inputCheckBox.push([this.id, 0]);
});
for (var i = 0; i < inputCheckBox.length; i++) {
alert(inputCheckBox[i]);
}
}
});
The above code will give me all the checkboxes on the webpage but I want the checkboxes only defined in the above HTML, and I also want to read the values of only those checkboxes which are checked. Please help.
GOAL: I am binding the dynamic HTML to the page its type might be checkbox or dropdown or text. Now I want to read the page labels and the values related to that labels. For ex my label(Gender value) has values of type checkbox so I just want to read the checked checkbox values related to that label.
UPDATE: At least tell me that how can I get the next element type
I am using the below code:
var type = $(this).closest('td').next().find('type').val();
ANY HELP
I think that all the markup has to be reviewed, but anyway, I think I know (please notice me if don't) what you want.
Try this:
// Read labels text
$("#tblCustomFields tr .label").each(function () {
var value = this.innerHTML;
console.log(this);
alert(value);
var inputCheckBox = new Array();
$(this).first().closest("td").next().find("input[type='checkbox']:checked").each(function(){
inputCheckBox.push($(this).next("label").text());
});
for (var i = 0; i < inputCheckBox.length; i++) {
alert(inputCheckBox[i]);
}
});
I'll make you a jsFiddle to test it.
Your question is confusing.
$("#tblCustomFields tr .label") - This will look for a child of TR with class label. Your HTML, shows that this resides inside td. If all the label elements have class label, you can refer each by -
$(".label).each(function(){
//do whatever you want
});
To get the element type next to the label with class label -
$(".label).each(function(){
var NextTd = $(this).parent().next(); // refers to the next td
$(NextTd).each(function(){
var type = $(this).find('input').prop('tagName');
//do whatever you want
});
});
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.