enable a disabled form - javascript

I have a form which is disabled using <fieldset disabled="disabled">. Now I want to enable the same form. I've used javascript but it isn't enabling my form. Here is my form and javascript code:
<?php echo "<input type='button' id='disable_enable_button' onclick='enableForm()' value='Enable/Disable'>"; ?>
<form id="form1>
<fieldset disabled="disabled">
<table>
<thead>
<tr>Sr no</tr>
<tr>Application</tr>
<tr>Comments</tr>
</thead>
<tbody>
<tr>1</tr>
<tr>ABC</tr>
<tr><textarea></textarea></tr>
</tbody>
</table>
</fieldset>
</form>
function enableForm() {
var form = document.getElementById("form1");
var elements = form.elements;
for (var i = 0, len = elements.length; i < len; ++i) {
elements[i].readOnly = "";
}
}

I see a few potential issues here. I don't know how different your code here is than your actual file, but make sure that your JavaScript code is wrapped with <script></script> tags. In addition to this, I never see a call to the function enableForm(), (again, could be different in your actual code), although I see the function showForm() call a few times. Make sure this function is called, probably upon some user action (ie button click).
Feel free to comment on this with any issues/corrections, and I will help resolve them!

Related

Toggle checkboxes on PHP table

I have a table with a checkbox in the table header, which will be used to toggle all the checkboxes below it. I've add a JavaScript function to the checkbox in the header, but so far it only selects the top checkbox (one checkbox) instead of all of them. Any suggestions or advice on what I've done wrong or what to research?
HTML table header code:
<thead>
<tr>
<th><center><input type="checkbox" value="" id="cbgroup1_master" onchange="togglecheckboxes(this,'cbgroup1')"></center></th>
<th>Sender</th>
<th>Receiver</th>
<th>Subject</th>
<th>Date</th>
</tr>
</thead>
PHP table code:
$table .= '
<tr>
<td><center><input type="checkbox" id="cb1_1" class="cbgroup1"></center></td>
<td>'.$sender.'</td>
<td>'.$receiver.'</td>
<td>'.$subject.'</td>
<td>'.$time.'</td>
</tr>';
Javascript code:
function togglecheckboxes(master,cn){
var cbarray = document.getElementsByClassName(cn);
for(var i = 0; i < cbarray.length; i++){
var cb = document.getElementById(cbarray[i].id);
cb.checked = master.checked;
}
}
The problem is you setting the same ID (cb1_1) to all the checkboxes (which is invalid in HTML) Id should be unique in the page. Thus, it only select the first found checkbox and discard the rest. To resolve this give unique ids to checkboxes.
$table .= '
<tr>
<td><center><input type="checkbox" id="cb1_'.$pmid.'" class="cbgroup1"></center></td>
<td>'.$sender.'</td>
<td>'.$receiver.'</td>
<td>'.$subject.'</td>
<td>'.$time.'</td>
</tr>';
Note: I just use the $pmid just as an example you should use appropriate value as per your scenario
I see 2 issues with you code.
(Probably) using the same id for multiple DOM elements
Your PHP code suggests that you are probably using a loop to create the checkboxes but you are using the same id for all of them "cb1_1".
Same as #atul here.
Improperly selecting your checkbox elements
Since you are using the same id for all inputs,
var cb = document.getElementById(cbarray[i].id);always returns the same element. A way to solve it is to use the solution provided by #atul
Another way is to rewrite your javascript as follows :
function togglecheckboxes(master,cn){
var cbarray = document.getElementsByClassName(cn);
for(var i = 0; i < cbarray.length; i++){
var cb = cbarray[i];
cb.checked = master.checked;
}
}
Your cbarray is already your checkboxes array, so it is redundant (aka useless) to call document.getElementById(cbarray[i].id) to get the element when you already have it with cbarray[i].

Javascript: display an alert when a form is checked?

I have created a simple web app that has 2 form selections, when the user makes their selection from each I want an alert to display showing them the choices they made.
I have attempted this below but when both forms are checked the alert is not displayed. What am I missing? Note see the comment:
//BELOW IS NOT BEING DISPLAYED BUT SHOULD BE
Current code:
<!DOCTYPE html>
<html>
<body>
<h1>Calculator</h1>
<p>Select the importance of this:</p>
<form method="get">
<input type="checkbox" name="Severity" value="negligible"> Negligible<br>
<input type="checkbox" name="Severity" value="minor"> Minor<br>
</form>
<p>Select the Probability of this:</p>
<form method="get">
<input type="checkbox" name="Probability" value="improbable"> Improbable<br>
<input type="checkbox" name="Probability" value="remote"> Remote<br>
<input type="checkbox" name="Probability" value="occasional"> Occasional<br>
<button onclick= "analyseThis()"> Analyse this </button> <br>
<script>
function analyseThis(){
var severities = document.getElementsByName('Severity');
var probs = document.getElementsByName('Probability');
var severity = undefined;
for(var i = 0; i < ages.length; i++)
{
if(severities[i].checked)
{
age = severities[i].value;
}
}
var probability = undefined;
for(var i = 0; i < probs.length; i++)
{
if(probs[i].checked)
{
probability = probs[i].value;
}
}
//BELOW IS NOT BEING DISPLAYED BUT SHOULD BE
alert("Severity is: " + age + "Probability is: " + probability);
}
</script>
</body>
</html>
I would use JQuery and use the click function of the button to submit.
Here is an example:
$(document).ready(function () {
$("{form id/class button id/class OR button id/class}").click(function(e) {
e.preventDefault();
//perform validation
//if everything is good...
$("{form id/class}").submit();
});
});
Something funny is happening:
Your function analyseThis() does get called, but there is an
error when it is being evaluated.
The form on the page is being "submitted", so the page reloads
and you never see the error.
To prevent the page from reloading (so you can see your error) do this:
Pass in the event object to your analyseThis() function from the onclick hander:
<button onclick= "analyseThis(event)"> Analyse this </button>
Make your analyseThis() accept the event object, and call .preventDefault() on it so that the page doesn't reload:
function analyseThis(e){
e.preventDefault()
// the rest of your function body here....
}
After you do that, you will see the underlying error output in the console:
ReferenceError: ages is not defined (line 33, col 17)
for(var i = 0; i < ages.length; i++)
If you do want the form to be submitted, just remember to remove the e.preventDefault() call after debugging the code.
You have an error in your code - you are checking ages.length in your loop which is probably undefined (no ages variable in your code) in the first loop and your code execution should stop there.
Working JSBin code here:
http://jsbin.com/yelihugune/1/
You have a bug in your code.
for(var i = 0; i < ages.length; i++)
{
if(severities[i].checked)
{
age = severities[i].value;
}
}
'ages' is not yet defined in your code, nor is 'age'. This will be throwing an error, stopping your code from running. This is why the alert is not going.
Declare the ages array.

quick html and JavaScript

<form action="#" onsubmit="return validateForm()" method="post">
<table>
<tr>
<td><p> 1. </p></td>
<td><label> I am cool </label></td>
<div class="allQuestion">
<?php for($i=1; $i<=10; $i++){?><td><input type="radio" name="Dquestion[1]" value="<?=$i?>"> <?=$i?> </td> <?php } ?>
</div>
</tr>
</table><!-- strength_table end -->
<input type="submit" value="Submit"><br/>
</form>
js
function validateForm(){
var questions = document.getElementsByClassName("allQuestion");
for( var j=0; j<questions.length; j++){
if( !isOneInputChecked(questions[j], "radio")){
formValid = false;
}
}
alert(formValid ? "Submisson succesful!" : "Submisson Failed");
return formValid;
}
function isOneInputChecked(sel){
var inputs = sel.getElementsByTagName('input');
for(var k = 0; k < inputs.length; k++){
if(inputs[k].checked)
return true;
};
return false;
};
i am using this to validate my radio question , it work perfectly but once i put the <td> before <input> , it work weird , i know it target the all input warp by allQuestion and td is blocking it.
any idea how i keep the td in place and make the script works ?
i tryed this code but didt work
var questions = document.getElementsByClassName("allQuestion").getElementsByTag("Td");
Avoid using table elements as a layout. I know it seems convenient when you first start off, but save yourself the trouble and just go straight into learning to style with css
function validateForm(){
var checked = document.querySelector('form').elements.some(function(el){
return el.checked;
});
if(checked){
//at least one is checked
} else {
//none are checked
}
}
I didn't exactly test this, but just try to give an id to the td that u are targeted.
var questions = document.getElementsByTag("id_name"); //id_name is the id of the td
*just extra notes, using table is not a good practice, use other simple HTML and CSS for more flexibilty and readble code.

Getting All HTML Checkboxes (Array) Checked with Javascript (and PHP)

I've been searching for this for a couple hours with no luck. This seems like it should be fairly easy but I am obviously overlooking something.
I have a table, with each row displaying information in each cell. At the end of each of the rows, there is an additional cell with a checkbox in it. The checkbox is an array, and each checkbox value is an imploded array via PHP. See below:
HTML/PHP
--------
(...some html code...)
<form method="post" action="the-next-page.php">
<table>
<tr>
<?php
(...some php SQL query code...)
while ($row = oci_fetch_array($result)) {
?>
<td><input type="text">Name</td>
<td><input type="text">City</td>
<td><input type="checkbox" name="checkGroup[]" value="<?php implode(":",$someArrayvariable) ?>"></td>
<?php
}
?>
</tr>
<tr>
<td><input type="submit" value="submit"></td>
</tr>
</table>
</form>
....
</html>
Passing the imploded values to the next page works fine. No problem there.
I have been trying to create a javascript function to check all of the boxes that are in this form, or under the checkbox group's name, or whatever I can do to check them all with the click of a button. I've tried variations of the following with no success:
HTML (On the top of the same script as above)
----
<button name="checkAll" onclick="checkAll()">Check All</button>
Javascript (On the bottom of the same script as above)
----
<script type="text/javascript">
function checkAll() {
var checks = document.getElementByName("checkGroup");
for (var i=0; i < checks.length; i++) {
checks[i].checked = true;
}
}
</script>
I can't figure out what I'm doing wrong. I know that a variation of this question has been asked before many times, but I don't seem to be getting any results. I'm guessing because my checkboxes name is an array (checkGroup[] ???).
When I click the button to check all of the checkboxes in the form, nothing happens.
Any ideas? Thanks in advance.
-Anthony
You can use JQuery to make this easier on yourself.
I would also assign a general class name to each checkbox input, so then in Javascript (using JQuery):
$(".classname").each(function() {
$(this).prop("checked",true);
});
I would also give the Check All button a unique class/id so you can do this
$(document).ready(function() {
$("#allcheckboxid").on("click",function() {
$(".classname").each(function() {
$(this).prop("checked",true);
});
});
})
Two minor things:
function checkAll() {
var checks = document.getElementsByName("checkGroup[]");
for (var i=0; i < checks.length; i++) {
checks[i].checked = true;
}
}
getElementByName should be getElementsByName, and checkGroup should be checkGroup[]. Other than that your code should be good to go!
Try this way to get all checked check box elements
<button name="checkAll" onclick="checkAll()">Check All</button>
<script type="text/javascript">
function checkAll() {
var checkboxes = document.getElementsByName('checkGroup[]');
var checkboxesChecked = [];
for (var i=0; i<checkboxes.length; i++)
{
if (checkboxes[i].checked) {
checkboxesChecked.push(checkboxes[i]);
}
}
return checkboxesChecked.length > 0 ? checkboxesChecked : null;
}
</script>

Loop through form input fields with Javascript

Please help me out on this. I have Javascript like the following:
function calc() {
var table = document.getElementById(tableNum);
var rowCount = table.rows.length;
for (var i = 0; i < rowCount; i++) {
var totalNum[i] = document.formNum.txt1[i].value * document.formNum.txt2[i].value;
document.getElementById('totalCalc[' + i + ']').innerHTML = totalNum;
}
}
And HTML like this:
<table id="tableNum">
<form name="formNum" action="" id="formNum">
<tr>
<td><input type="text" name="txt1[]" onkeyup="calc()"/></td>
<td><input type="text" name="txt2[]" onkeyup="calc()"/></td>
<td><span id="totalCalc[]"></span></td>
</tr>
</form>
</table>
The number of input fields is unknown. No error, but totalCalc field is empty. Please tell me what I have done wrong. Thanks.
EDIT: I'm sorry, I forgot to mention both the input fields are in a table. Please check the edited code. Thanks.
EDIT: I'm actually working on a demo which the number of table row is defined by user, by clicking insert row button.
EDIT: Thanks Travis for the code. After a few changes, the code is working now. But only the first row is working. I'm thinking to get the length of the row and to use for loop for the text fields. <input type="text" name="txt1[<?php echo $rowLength;?>]" onkeyup="calc()"/> Does anyone have other ideas? Thanks.
The first thing seems wrong is
document.getElementById(tableNum);
should be
document.getElementById("tableNum");
Secondly,
var totalNum[i] =
should be
var totalNum =
Also, its not working, you can find it out quickly by debugging through firebug or chrome's integrated developer tool. Which will help you for syntax verification as well.
Here is what is going on.
HTML first
If you are going to reference these by indices, then use proper indices, like this
name="txt1[0]"
name="txt2[0]"
<span id="totalCalc[0]">
Javascript
document.getElementById(tableNum);
getElementsById expects a string, so this should be
document.getElementById("tableNum");
Since you are iterating, you only need one of these variables since it is immediately used (not a whole array):
var totalNum = instead of var totalNum[i]
When you access the form using dot notation, the brackets in the name messes that up, you need to do it like this:
document.formNum["txt1["+i+"]"].value instead of document.formNum.txt1[i].value
Vuala
When you make these minor changes, the code you used will actually produce proper results :) See this working demo: http://jsfiddle.net/69Kj7/ , also, here is a demo with 2 rows: http://jsfiddle.net/69Kj7/1/
For reference, this is the code in the demo:
html:
<table id="tableNum">
<form name="formNum" action="" id="formNum">
<tr>
<td><input type="text" name="txt1[0]" onkeyup="calc()"/></td>
<td><input type="text" name="txt2[0]" onkeyup="calc()"/></td>
<td><span id="totalCalc[0]"></span></td>
</tr>
</form>
</table>​
js:
function calc() {
var table = document.getElementById("tableNum");
var rowCount = table.rows.length;
for (var i = 0; i < rowCount; i++) {
var totalNum = document.formNum["txt1["+i+"]"].value * document.formNum["txt2["+i+"]"].value;
document.getElementById('totalCalc[' + i + ']').innerHTML = totalNum;
}
}​
if you wants to work with pure java script and here is the logical code
html
<form name="formNum" id="formNum" action="" >
<input type="text" name="foo[]" onkeyup="calc()" value="5"/>
<input type="text" name="foo[]" onkeyup="calc()" value="12"/>
<span id="totalCalc"></span>
</form>
​
js
var inputs = formNum["foo[]"];
var total = 1;
alert(inputs.length);
for (var i = 0; i < inputs.length; i++) {
total *= inputs[i].value;
}
alert(total);
working DEMO
I've figured out how to solve the problem. Just insert array after totalCalc, but not within totalCalc.
Thank you guys so much for helping me out :)

Categories