How to set the style and disable/enable buttons using JavaScript - javascript

Based on my code I have grayed out my images using the CSS (with #myImage)
and I am trying for the following
Need to set or remove the style when two ore more check boxes are checked so that the images are clear and bright (I mean with no gray/white background on the images)
And make the image buttons active.
I am trying to do that by getElementById, getElementsByname and can not get it right.
Can you please help with this and attached is the code.
Thanks in advance.
<html>
<head>
<title>Untitled Document</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<script language="JavaScript">
function countCheckboxes ( ) {
var form = document.getElementById('testForm');
var count = 0;
for(var n=0;n < form.length;n++){
if(form[n].name == 'itemID[]' && form[n].checked){
count++;
}
}
if(count >2)
{
document.getElementById('myimage').style = "none";
//document.getElementById('checkCount').innerHTML = count;
document.getElementsByname('testing').disabled = false;
document.getElementsByname('testing1').disabled = false;
alert("total no of checkbox selected "+count)
}
else
{
document.getElementsByname('testing').disabled = true;
document.getElementsByname('testing1').disabled = true;
}
}
/*
function diableQuoteBtns()
{
document.getElementById('itembutton').disabled = false;
}*/
</script>
</head>
<style>
#myImage {
opacity: 0.5;
filter: alpha(opacity=40); /* msie */
}
/* or */
#wrapper {
opacity: 0.5;
filter: alpha(opacity=40); /* msie */
background-color: #0000;
}
</style>
<body >
<form name="form1" id="testForm">
<table>
<tr>
<td> <input type="checkbox" name="itemID[]" id="item1" value="1" onclick="countCheckboxes()" >
<input type="checkbox" name="itemID[]" id="item2" value="2" onclick="countCheckboxes()" >
<input type="checkbox" name="itemID[]" id="item3" value="3" onclick="countCheckboxes()" >
<input type="checkbox" name="itemID[]" id="item4" value="4" onclick="countCheckboxes()" >
</td>
<td><span class='my_class_item'>Item Name : </span></td>
</tr>
</table>
<table>
<tr>
<td align="center" colspan="6">
<!---<div id="wrapper"><img id="myImage" src="button_quote.gif" alt="" border="0" align="middle"></div>
<span class='my_class_item'><span class='bold'>-OR-</span></span>
<div id="wrapper"><img id="myImage" src="button_quote.gif" border="0" align="middle"></div>--->
<input type="image" disabled name="Testing" id="myimage" src="button_quote.gif" border="0" align="middle" onClick="JavaScript:validateForm('myAction1');">
<input type="image" disabled name="Testing1" id="myimage" src="button_quote.gif" border="0" align="middle" onClick="JavaScript:validateForm('myAction2');">
</div>
</td>
</tr>
</table>
</form>
</body>
</html>

Check the Fiddle example here. the code is a bit messy but the main issue was that when you execute document.getElementsByName("Testing") this gives you a collection of the elements with that name, so you need to iterate them and perform whatever actions you want on each one individually like so:
var imgElements = document.getElementsByName("Testing");
for (var i = 0, max = imgElements.length; i < max; i++) {
imgElements[i].disabled = false
}
Other than that you are doing fine.

JQuery is an incredibly popular library, and for a good reason: it makes tasks like this trivial.
If you just download the latest version of jQuery (from www.jquery.com) and add it to the page you can set the disabled attribute and element styles very easily.
For example:
$('[name="testing"], [name="testing1"]').attr('disabled', 'disabled');
$('#myimage').css('display', 'none');
If, for whatever reason, you don't want to use jQuery, you can use the setAttribute method to set attributes directly:
document.getElementsByname('testing')[0].setAttribute('disabled', 'disabled');
Or, to set styles you just have to pick a particular style property and set it; for instance:
document.getElementById('myimage').style.display = "none";
For further info see:
https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Getting_started/JavaScript

Related

JavaScript enable button when checkbox checked

I need to have this button disabled, and when the user checks a checkbox it needs to be enabled its just not working for me at all, the button stays disabled, i know the onclick is calling the script because i placed an alert in the script and it does alert me....
<script type="text/javascript">
function goFurther(){
if (document.getElementById("ID").checked == true)
document.getElementById("Calculate").disabled = false;
else
document.getElementById("Calculate").disabled = true;
}
</script>
<style type="text/css">
input[disabled]
{
color:Gray; text-decoration:none;
}
</style>
<CFOUTPUT query = "qGetOpenItemsTrans">
<TR>
<TD ALIGN = "CENTER">
<input type="checkbox" name = "chkbx" id='#ID#' value="#seq_claim_id#" onClick="goFurther()" unchecked = 0 >
</TD>
<TD ALIGN = "CENTER">#Inventory_Date#</TD>
<TD ALIGN = "CENTER">#seq_claim_id#</TD>
<TD ALIGN = "CENTER">#Month_Closed#</TD>
<TD ALIGN = "CENTER">#Amount_Rcvd_by_FRG#</TD>
<TD ALIGN = "CENTER">#Commission_Amt#</TD>
<TD ALIGN = "CENTER">#Net_Recovery#</TD>
</TR>
<INPUT TYPE ="Button" NAME = "Calculate" VALUE = "Calculate" onClick = "FormSubmit();" style="height:35px; width:150px; font-size:medium; font-weight:bold; color:green;" disabled >
You are calling document.getElementById("Calculate"), but your button does not have an id of "Calculate".
id="Calculate"
In addition to your name attribute needing replaced by (or added with) id attibute, your function is also trying to get an element with the ID value of id. However, your IDs are dynamic via your query loop. Pass the clicked element itself to the goFurther function so you have direct reference to the checked element.
<input type="checkbox" name="chkbx" id='#ID#' value="#seq_claim_id#" onClick="goFurther(this)" >
<INPUT TYPE="Button" id="Calculate" VALUE="Calculate" onClick="FormSubmit();" style="height:35px; width:150px; font-size:medium; font-weight:bold; color:green;" disabled >
<script>function goFurther(elem){
if (elem.checked == true)
document.getElementById("Calculate").disabled = false;
else
document.getElementById("Calculate").disabled = true;
}</script>
You may also simplify your function further by doing the following:
function goFurther(elem){
document.getElementById("Calculate").disabled = !elem.checked;
}
UPDATE:
To your styling issue. this is due to how CSS works. You have a disabled style selector defined in your CSS, but your in-line style is set to color: green which will always take presidence over any defined stylesheets.
<style>
input#Calculate {
color:green;
}
input#Calculate[disabled]
{
color:Gray; text-decoration:none;
}
</style>
<INPUT TYPE="Button" id="Calculate" VALUE="Calculate" onClick="FormSubmit();" style="height:35px; width:150px; font-size:medium; font-weight:bold;" disabled >
You seems to be confused with the attributes "name" and "id".
The attribute "id" give you access to an element (tag)
The attribute "name" defines on form child elements (like input, button) the name of the value.
In your case you should change to
...
<input type="checkbox" name = "chkbx" id='ID'
onClick="goFurther(this); return false;">
...
<script type="text/javascript">
function goFurther(self){
document.getElementById("Calculate").disabled = !self.checked;
}
</script>
I guess this way it much easier to read (but still untested)
<INPUT TYPE ="Button" ID = "Calculate" NAME = "Calculate" VALUE = "Calculate"
onClick = "FormSubmit();" style="height:35px; width:150px; font-size:medium;
font-weight:bold; color:green;" disabled >

How to dynamically change css style based on INPUT value?

We have some data that user enters and the result after calculation. Now I want depending on the value that the user gets after calculation to change css style.
My html:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<style type="text/css">
.not_good { solid red; background:#eee;}
.good { solid green; background:#C0E9F6;}
</style>
<script type="text/javascript">
var BuckwheatCa = 4
function convcase(word) {
document.convert.Ca.value = BuckwheatCa * document.convert.Buckwheat.value
};
</script>
</head>
<body>
<FORM ACTION="#" NAME="convert">
Buckwheat, gramm
<INPUT TYPE=TEXT NAME="Buckwheat"
ONKEYUP="convcase(document.convert.Buckwheat.value)" >
<table>
<tr>
<td>Ca</td> <td><INPUT TYPE=TEXT NAME="Ca" DISABLED></td>
</tr>
</table>
</FORM>
</body>
</html>
so is there a way to create a function with if...else statement using document.convert.Ca.value variable value witch will change css style of text in <td> if the variable is < 10 for example?
You can do it using normal javascript using this in your code
if(value<10){
document.getElementById("sample").style.color="blue";
}
OR You can do it using jQuery:
if(value<10){
$("sample").css("color","blue");
}
Choose whichever appeals to you.
Of course you must have IDs as #Barmar suggested:
<td id='sample'>Ca</td> <td><INPUT TYPE=TEXT NAME="Ca" DISABLED></td>
The above code now changes the style of Ca alone as the id exists for that tag.
And you can make changes to any of the css properties: http://www.blooberry.com/indexdot/css/propindex/all.htm
function convcase(word) {
document.convert.Ca.value = BuckwheatCa * document.convert.Buckwheat.value
// now add css comparison
if(document.convert.Ca.value < 10){
// using jQuery to access the 'td' and set the css on it
$('td').css('font-family', 'arial');
} else {
// whatever you want
}
};

accessing selected radio button value inside iframe [duplicate]

This question already has answers here:
Accessing Elements Inside iframe and body Tags with JavaScript
(2 answers)
Closed 10 years ago.
I write the code. Where I am trying to write a form which is having a long list of radio button content inside 'iframe' like below:
<form name="iframeform" method="POST" action="http://localhost/cgi-bin/run">
<tr>
<td><iframe id="macList" src="http://localhost/macinfo" style="width:1000px;height:160px">
</iframe></td>
</tr>
<tr>
<input type="hidden" name="macaddr" value="">
<td><input type="submit" name="macselect" value="Continue" id="stdbtn" onclick="getIframeContent()"></td>
</tr>
</form>
'iframe' is pointing to macinfo page is having code like below:
<html>
<body>
<table>
<tr>
<td><input type=radio name=mac value=E8:B7:48:7B:C0:4A>abc.example.com</td>
</tr>
<tr>
<td><input type=radio name=mac value=00:17:08:5A:81:CF>xyz.cisco.com</td>
</tr>
....
</table>
</body>
</html>
How can I write "getIframeContent()" function to fetch the value of selected radio button? please help..
Long story short. To access iframe document use .contentWindow.document, i.e.:
document.getElementById('macList').contentWindow.document
And an example code:
<html>
<head>
<script type="text/javascript">
function getIframeContent(){
var myIFrame = document.getElementById('macList');
var myIFDoc = myIFrame.contentWindow.document;
var myRadios = myIFDoc.getElementsByName("mac");
var checkedItemValue = "";
for(var i=0; i<myRadios.length; i++) {
if (myRadios[i].checked) {
checkedItemValue = myRadios[i].value;
}
}
if (checkedItemValue) {
alert(checkedItemValue);
} else {alert('Select address');}
}
</script>
</head>
<body>
<iframe id="macList" src="..."
style="width:600px;height:160px">
</iframe>
<input type="submit" onclick="getIframeContent();">
</body>
</html>
You will have to get the array of mac using document.getElementsByName and loop over them:
var allRadios = document.getElementsByName("mac");
var checkedItem;
for(var i=0; i<allRadios.length; i++) {
if (allRadios[i].checked) {
checkedItem = allRadios[i];
alert('Found checked radio button');
}
}
You could then pass checkedItem to your getIframeContent function.
Edit
You could share the checkedItem variable across two pages by using window
window.checkedItem = allRadios[i];

With Javascript convert disabled input fields into readonly input fields

I have a problem with a form in IE. I have disabled fields in form i,e. field having property disabled="disabled". These fields show the input text in grey color and that looks very dull/blurred and if i try apply css changes to such fields, it will not work for IE, but works for other browsers like chrome, firefox.
Is there any way to make the text to better font color here?
I thought one way of doing this is removing property disabled="disabled" and add property readonly="readonly" with javascript. If this is possible then how can i do this with Javascript. I am new to Javascript, so please help me
Below HTML to explain the behaviour. Run this in both IE and other browser to see the difference.
<html>
<head>
<style type="text/css">
.col {
background-color: yellow;
color: red;
}
</style>
</head>
<body>
<table>
<tr>
<td>Editable field: </td>
<td>
<input type="text" id="editable-field-id" value="Editable field" class="col"/>
</td>
</tr>
<tr>
<td>Disabled field: </td>
<td>
<input type="text" disabled="disabled" id="disabled-field-id" value="Disabled field" class="col" />
</td>
</tr>
<tr>
<td>Readonly field: </td>
<td>
<input type="text" readonly="readonly" id="readonly-field-id" value="Readonly field" class="col"/>
</td>
</tr>
</table>
</body>
</html>
I am testing this in IE9.
You can change disabled input fields into readonly ones by using the .prop() method available in jQuery. I typically discourage the use of .attr(), and this is why.
$(function (){
$('input').prop({
'disabled': false,
'readonly': true
});
});
Although the method .removeProp() is available, documentation encourages refrain when using it, because, to quote, it "will remove the property completely and, once removed, cannot be added again to element. Use .prop() to set these properties to false instead."
View demo here: http://jsfiddle.net/teddyrised/tE98z/
document.getElementById("your_field").readOnly=true;
or, with jQuery:
$('#your_field').attr('readonly', true);
<html>
<head>
<style type="text/css">
.col {
background-color: yellow;
color: red;
}
</style>
</head>
<body>
<table>
<tr>
<td>Editable field: </td>
<td>
<input type="text" id="editable-field-id" value="Editable field" class="col"/>
</td>
</tr>
<tr>
<td>Disabled field: </td>
<td>
<input type="text" disabled="disabled" id="disabled-field-id" value="Disabled field" class="col" />
</td>
</tr>
<tr>
<td>Readonly field: </td>
<td>
<input type="text" readonly="readonly" id="readonly-field-id" value="Readonly field" class="col"/>
</td>
</tr>
</table>
<script type = "text/javascript">
document.getElementById("disabled-field-id").disabled = false;
document.getElementById("disabled-field-id").readOnly = true;
</script>
</body>
</html>
Use the setAttribute property. Note in example that if select 1 apply the readonly attribute on textbox, otherwise remove the attribute readonly.
http://jsfiddle.net/baqxz7ym/2/
document.getElementById("box1").onchange = function(){
if(document.getElementById("box1").value == 1) {
document.getElementById("codigo").setAttribute("readonly", true);
} else {
document.getElementById("codigo").removeAttribute("readonly");
}
};
<input type="text" name="codigo" id="codigo"/>
<select id="box1">
<option value="0" >0</option>
<option value="1" >1</option>
<option value="2" >2</option>
</select>
if you disable the inputs programmatically can set style as you want
try it:
//bloqueo todos los radiobuttons y checkboxs
//block all radiobuttons and checkbox
jQuery(document).on("change", 'input:checkbox.yourClass,input:radio.yourClass', function () {
jQuery(this).prop("checked", false);
});
//bloqueo campos de texto
//block all text fields
jQuery(document).on("focusin", 'input.yourClass, textarea.yourClass', function () {
jQuery(this).blur();
});
//bloqueo selects
//block all selects
jQuery(document).on("focusin", 'select.yourClass', function (event) {
var $selectDiabled = jQuery(this).attr('disabled', 'disabled');
setTimeout(function(){ $selectDiabled.removeAttr("disabled"); }, 30);
});
if you want set style they aren't technically disabled
here can see the original code: https://jsfiddle.net/9kjqjLyq/
You need to depend on a pure javascript(preferrably jQuery) solution.
Add a custom attribute to all your controls:
<input type="text" disabled="true" />
Now you can check if they are disabled and you can proceed to block them using javascript:
var value = yourTextBox.value; //the last value that the control holds,
//before it was disabled?
$('yourTextBox').click(function() {
value = $(this).value;
});
$('yourTextBox').blur(function() {
if($(this).attr('disabled') == 'true')
$(this).value = value;
});
To add more strictness, add another function:
$('yourTextBox').keypress(function() {
if($(this).attr('disabled') == 'true')
$(this).value = value;
});
If you want something simple, I would recommend this:
$('yourTextBox').keypress(function() {
if($(this).attr('disabled') == 'true')
return false;
});

hiding div based on unchecking checkboxes

I have multiple checkboxes in a form. Based on clicking those checkboxes, I show a div section. But if I uncheck even one checkbox, that div section gets hidden. How do I make sure that div section is hidden only if all checkboxes are unchecked. Crude way can be to write my own 'display' method which will check if all checkboxes are unchecked and then hide the div section. Any easier solution??
HTML:
<input type="checkbox" class="group" name="check1">
<input type="checkbox" class="group" name="check2">
<input type="checkbox" class="group" name="check3">
<input type="checkbox" class="group" name="check4">
jQuery:
$(function() {
var $checks = $('input:checkbox.group');
$checks.click(function() {
if($checks.filter(':checked').length == 0) {
$('#div').hide();
} else {
$('#div').show();
}
});
});
The following code will show the div if one or more checkboxes has been checked:
jQuery
Version 1:
$("input[name='mycheckboxes']").change(function() {
$("#showme").toggle($("input[name='mycheckboxes']:checked").length>0);
});
Version 2 (more efficient):
var MyCheckboxes=$("input[name='mycheckboxes']");
MyCheckboxes.change(function() {
$("#showme").toggle(MyCheckboxes.is(":checked"));
});
HTML
<input type="checkbox" name="mycheckboxes" />
<input type="checkbox" name="mycheckboxes" />
<input type="checkbox" name="mycheckboxes" />
<input type="checkbox" name="mycheckboxes" />
<div id="showme" style="display: none">Show me</div>
Code in action (Version 1).
Code in action (Version 2).
--- Different Checkbox Names Version ---
For different named checkboxes, wrap them in a DIV with an identifier. E.g.
jQuery
var MyCheckboxes=$("#checkboxgroup :checkbox");
MyCheckboxes.change(function() {
$("#showme").toggle(MyCheckboxes.is(":checked"));
});
HTML
<div id="checkboxgroup">
<input type="checkbox" name="mycheckbox1" />
<input type="checkbox" name="mycheckbox2" />
<input type="checkbox" name="mycheckbox3" />
<input type="checkbox" name="mycheckbox4" />
</div>
<div id="showme" style="display: none">Show me</div>
This code in action.
Not really, you need Javascript for this one... Or maybe... Let's say:
<html>
<head>
<style type="text/css">
#input_container > input + input + input + div {display:none}
#input_container > input:checked + input:checked + input:checked + div {display:block}
</style>
</head>
<div id="input_container">
<input type="checkbox">blah1
<input type="checkbox">blah2
<input type="checkbox">blah3
<div>To show/hide</div>
</div>
</body>
</html>
I'd create a function that uses a variable that tracks the number of checkboxes checked:
var numberOfChecks = 0;
function display(ev) {
var e = ev||window.event;
if (this.checked) {
numberOfChecks++;
} else {
numberOfChecks--;
}
if (!numberOfChecks) {
//hide div code
} else {
//display div code
}
}
Use that function for each onClick event for every checkbox. In the ideal world this would be done inside some initialization function so that numberOfChecks and display aren't in the global namespace.
Plain Javascript:
HTML
<div id="checkboxes">
<input type="checkbox" name="check1">
<input type="checkbox" name="check2">
<input type="checkbox" name="check3">
<input type="checkbox" name="check4">
</div>
<div id="hiddendiv"><!-- more stuff --></div>
Javascript
(function() { //Create clousre to hide the checked variable
var checked = 0;
var inputs = document.getElementById('checkboxes').getElementsByTagName('input');
for (var i=0, l=inputs.length; i<l; i++) {
if (inputs[i].type == 'checkbox') {
if (inputs[i].checked) checked++; //Count checkboxes that might be checked on page load
inputs[i].onchange = function() {
checked += this.checked ? 1 : -1;
var hiddendiv = document.getElementById('hiddendiv');
if (!checked) hiddendiv.style.display = "none";
else hiddendiv.style.display = "";
};
}
}
}());
The other option is to simply iterate through each checkbox every time the change event is fired rather than relying on counting, which is probably more error prone. Obviously jQuery is more concise, but a little verbosity never hurt anyone.
function toggleCheckbox(id) {
if ($("input[id=" + id + "]").is(':checked')) {
$( "#"+id ).prop( "checked", false );
} else {
$( "#"+id ).prop( "checked", true );
}
}
Just pass the id of your checkbox

Categories