Toggle visibility of html using javascript checkbox event - javascript

I've cobbled together these javascript functions to hide the delivery address fields on my shopping cart address form if goods are going to billing address. The functions toggle visibility of html wrapped by ..
function getItem(id) {
var itm = false;
if(document.getElementById)
itm = document.getElementById(id);
else if(document.all)
itm = document.all[id];
else if(document.layers)
itm = document.layers[id];
return itm;
}
function showHideItem(id) {
itm = getItem(id);
if(!itm)
return false;
if(itm.style.display == 'none')
itm.style.display = '';
else
itm.style.display = 'none';
return false;
}
It works fine if were loading a new address form, the problem I have is if they submit the form with checkbox ticked, and validation fails, the form reloads with the checkbox ticked but unfortunately the fields are visible so now the removing the checkbox hides the fields!!
<tr><td class="white"><strong>Delivery Address</strong></td>
<td>Tick <input Type="checkbox" id="deliver_same" value="yes" onClick="showHideItem('delAddress')" />
If delivery address is billing address</td></tr>
<tbody id="delAddress">
<tr><td>Address line 1</td><td><input class="text" name="saddr1" value="" /></td></tr>
...
<tr><td>Post /Zip Code</td><td><input class="text" name="spostalcode" value="" /></td></tr>
</tbody>
I guess what I need is an onload event which hides the fields if checkbox is ticked when the form loads. Having just written that, I might have a go but not confident. Please, no mention of jquery, its not an option at this point of project.

function checkDeliverSame() {
var deliverSame = getItem('deliver_same');
var deliveryAddress = getItem('delAddress');
if (deliverSame.checked) {
deliveryAddress.style.display = 'none';
} else {
deliveryAddress.style.display = 'block';
}
}
checkDeliverSame(); /* This runs the function on page load */
Put that function, along with your getItem function, right above the </body> tag, and call it in the checkbox input onclick. You will also need to change the id#delAddress element from a tbody to a div so that the getItem function will work on it.
Here's a fiddle: http://jsfiddle.net/JuNhN/1/

I modified Josh's function to make it more generic, prefer document.getElementById() too as it fits in better with itm.style.display. I don't entirely trust checkDeliverSame(); going for a direct call in the html shortly after the closing tag.
function checkHiddenRows(id) {
deliverSame = getItem('deliver_same');
itm = document.getElementById(id);
if (deliverSame.checked == true) {
itm.style.display = 'none';
} // else { alert('Checkbox not checked') } // Verify the checkbox state
}
<script>checkHiddenRows('deliveryAddress');</script>
The form is now working as intended.

Related

Disabled or remove onClick attributes of the button if a certain field is empty in SuiteCRM

Good Day!
I am planning to add a javascript where it will remove the onclick attribute if a certain field is empty. BTW I modify my code because I use different approach on this:
First I added a after_ui_frame logic hook and call the javascript using the custom logic hook.
$randomNumber = rand();
echo '<script type = "text/javascript">
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "custom/include/CustomLogicHook/clearFields.js?v=' . $randomNumber . '";
document.body.appendChild(script);
</script>';
And my custom JS
$("#btn_custom_city_c").attr("disabled", true);
$("#btn_custom_barangay_c").attr("disabled", true);
$('#dvt2_province_id_c').keyup(function() {
if ($(this).val().length !=0)
$("#btn_custom_city_c").attr("disabled", false);
else
$("#btn_custom_city_c").attr("disabled", true);
});
The disabled/enabled button works but it won`t work on relate field. This codes only works on a normal field
I think this code is generated by a builder or something. right? what a mess!
Anyway, you can check if the input value length is == 0. without any jquery. but be aware that:
1- function triggers after you leave the input after the change.
2- white space means that the input value length is more than 0
let changeListener = document.getElementById("input").addEventListener("change", function() {
let input = document.getElementById("input");
if (input.value.length == 0) {
document.getElementById("btn").disabled = true;
} else {
document.getElementById("btn").disabled = false;
}
})
<input type="text" id="input">
<button type="button" id="btn">button</button>
Edit: regarding your comment:
yes, you can start the button disabled. just disabled it on load out of the function.
document.getElementById("btn").disabled = true;
let changeListener = document.getElementById("input").addEventListener("change", function() {
let input = document.getElementById("input");
if (input.value.length == 0) {
document.getElementById("btn").disabled = true;
} else {
document.getElementById("btn").disabled = false;
}
});
<input type="text" id="input">
<button type="button" id="btn">button</button>
just incase you are working with Suite CRM I was able to implement the behavior I want on my buttons.
I added this code below:
if($('#province_c').val() == " "){
$("#btn_custom_city_c").attr('disabled', true);
}else{
$("#btn_custom_city_c").attr('disabled', false);
}
var inputName = "input[name='province_c']";
YAHOO.util.Event.addListener(YAHOO.util.Selector.query(inputName), 'change',
function(){
$("#btn_custom_city_c").attr('disabled', false);
});
for more information you can check at Suite CRM community click Here

How do I make an onclick event for a dynamically added checkbox? (JavaScript)

I'm new to html and learning through YouTube and such. I'm writing a JavaScript which allows me to show a custom window with checkboxes and textboxes (and labels) on it. I disabled the textboxes to begin with, but I would like them to be enabled when the corresponding checkboxes are checked.
I've searched on the internet for a solution, already tried using:
document.getElementById('chb1').onclick = function() { //my function };
or
document.getElementById('chb1').onclick = //my function;
but neither of them works.
function MyCheckboxWindow()
{
this.render = function(func,titel,dialog,checktext1)
{
var dialogboxbody = document.getElementById ('dialogboxbody');
dialogboxbody.innerHTML = dialog + ': <br>';
if(checktext1 != null)
{
dialogboxbody.innerHTML +='<br><input type="checkbox" id="chb1"><label for="chb1" class="lbl" id="lbl1"></label>'
+ '<label for="txt1">€</label> <input type="text" id="txt1" value="0,00" disabled>';
document.getElementById('lbl1').innerHTML = checktext1 + ': ';
document.getElementById('chb1').onclick = alert('');
}
else if(!checkboxCheck)
{
dialogboxbody.innerHTML +='<br><input type="checkbox" id="chb1"><label for="chb1" class="lbl" id="lbl1"></label>'
+ '<label for="txt1">€</label> <input type="text" id="txt1" value="0,00" disabled>';
document.getElementById('lbl1').innerHTML = "Other: : ";
document.getElementById('chb1').onclick = Change.ischanged('chb1');
checkboxCheck = true;
}
document.getElementById('dialogboxfoot').innerHTML = '<button onclick="CheckboxWindow.ok(\''+func+'\')">Ok</button> <button onclick="CheckboxWindow.cancel()">Cancel</button>';
}
}
var CheckboxWindow = new MyCheckboxWindow();
function CheckboxChanged()
{
this.ischanged(id)
{
alert('');
}
}
var Change = new CheckboxChanged();
Just for info, there should be 6 of these checkboxes, but I left them out in this example. Also, in the "if", I replaced my function by an alert. The code in the if-clause produces an alertbox only when I open the custom window, clicking the checkbox doesn't do anything (but tick the box).
Writing it like I did in the "else if" in this example, doesn't produce anything at all, nor does function() { Change.ischanged('chb1'); } (like I said before).
Please tell me why this isn't working. There's probably a better way of adding these checkboxes as well, so if you know any, please let me know as well.
Hope this helps as a starting point:
//Dynamically create a checkbox, and add it to a div.
//appendChild() works for other types of HTML elements, too.
var div = document.getElementById("div");
var checkbox = document.createElement("input");
checkbox.type = "checkbox";
checkbox.id = "checkbox_1";
div.appendChild(checkbox);
var textbox = document.createElement("input");
textbox.type = "text";
textbox.disabled = true; //programmatically disable a textbox
div.appendChild(textbox);
//do something whenever the checkbox is clicked on (when user checks or unchecks it):
checkbox.onchange = function() {
if(checkbox.checked) { //if the checkbox is now checked
console.log("checked");
textbox.disabled = false;
}
else {
console.log("unchecked");
textbox.disabled = true; //programmatically disable a textbox
}
}
<div id='div'></div>
Thanks for your reply and I'm sorry for responding this late, I was quite busy the past 2 weeks and didn't have a lot of time.
I've tried to use your sample code but was unable to make it work. However, I was able to get it working by adding "onclick="Change.ischanged()" to the input in the if statement. I'm sure I tried something like that before, but I probably typed "CheckboxWindow" or "CheckboxChanged" instead of "Change" by mistake.
if(checktext1 != null)
{
dialogboxbody.innerHTML +='<br><input type="checkbox" id="chb1" onclick="Change.ischanged()"><label for="chb1" class="lbl" id="lbl1"></label>'
+ '<label for="txt1">€</label> <input type="text" id="txt1" value="0,00" disabled>';
document.getElementById('lbl1').innerHTML = checktext1 + ': ';
}
I know that adding the objects like this isn't the best way, but I seem to be having trouble trying to achieve my goal in your way.
I also changed "this.ischanged(id)" to "this.ischanged = function()" (I also made it so I don't need to pass the id anymore).
Try the OnClick event instead of the OnChange event for the checkbox.
//Dynamically create a checkbox, and add it to a div.
//appendChild() works for other types of HTML elements, too.
var div = document.getElementById("div");
var checkbox = document.createElement("input");
checkbox.type = "checkbox";
checkbox.id = "checkbox_1";
div.appendChild(checkbox);
var textbox = document.createElement("input");
textbox.type = "text";
textbox.disabled = true; //programmatically disable a textbox
div.appendChild(textbox);
//do something whenever the checkbox is clicked on (when user checks or unchecks it):
checkbox.onclick = function() {
if(checkbox.checked) { //if the checkbox is now checked
console.log("checked");
textbox.disabled = false;
}
else {
console.log("unchecked");
textbox.disabled = true; //programmatically disable a textbox
}
}
<div id='div'></div>

using only javascript to prompt user to choose at least one checkbox

Hello I have a HTML form which already prompts users to fill empty fields. And this is the script that I am using:
<!-- Script to prompt users to fill in the empty fields -->
<script type="text/javascript">
document.addEventListener("DOMContentLoaded", function() {
var elements = document.getElementsByTagName("INPUT");
for (var i = 0; i < elements.length; i++) {
elements[i].oninvalid = function(e) {
e.target.setCustomValidity("");
if (!e.target.validity.valid) {
e.target.setCustomValidity("To continue, you must correctly fill in the missing fields.");
}
};
elements[i].oninput = function(e) {
e.target.setCustomValidity("");
};
}
});
</script>
This script works flawlesly and it brings up a nice prompt that looks like this:
It works for all the input text fields, but I need another script that will (a) check if at least one checkbox you can see at the bottom of the form is checked, and (b) will bring up a prompt which is styled the same way as the one above.
I looked at other posts and wrote the below script. I referenced checkboxes by their IDs and somehow used the function function(e) from the above script. Well it won't work for me but I must be close...
<!-- Script which prompts user to check at least one checkbox -->
<script type="text/javascript">
document.addEventListener("DOMContentLoaded", function() {
if (
document.getElementById("linux-c-arm-checkbox").checked == false &&
document.getElementById("linux-eda-cad-checkbox").checked == false &&
document.getElementById("linux-blender-checkbox").checked == false &&
document.getElementById("linux-photo-checkbox").checked == false &&
document.getElementById("linux-audio-checkbox").checked == false &&
document.getElementById("linux-latex-checkbox").checked == false &&
document.getElementById("linux-desktop-checkbox").checked == false &&
document.getElementById("linux-office-checkbox").checked == false
){
function(e) {
e.target.setCustomValidity("");
if (!e.target.validity.valid) {
e.target.setCustomValidity("Please choose at least one checkbox.");
}
}
}
});
</script>
Can anyone help me solve this by using javascript without JQuery?
Though there is no way you can put required attribute on a checkbox group and do the validation for atleast one selection, here is a workaround solution. Do the changes accordingly on your HTML.
It takes a hidden textbox as the placeholder of the selected checkbox group. If atleast one is selected the hidden field will also have the value.
function setAccount() {
if (document.querySelectorAll('input[name="gender"]:checked').length > 0)
document.querySelector("#socialPlaceholder").value = document.querySelector('input[name="gender"]:checked').value;
else
document.querySelector("#socialPlaceholder").value = "";
}
function invalidMsg(textbox) {
if (textbox.value == '') {
textbox.setCustomValidity('Please select at least one account');
} else {
textbox.setCustomValidity('');
}
}
<form target="_blank">
<b>Accounts</b>
<input type="text" id="socialPlaceholder" required value="" style="width:0px;height:0px;position: relative;left:-30px;opacity: 0;" oninvalid="invalidMsg(this)"/><br/>
<label>Facebook<input type="checkbox" name="gender" value="facebook" onClick="setAccount()"/></label>
<label>Twitter<input type="checkbox" name="gender" value="twitter" onClick="setAccount()"/></label>
<label>Google Plus<input type="checkbox" name="gender" value="google_plus" onClick="setAccount()"/></label>
<label>Instagram<input type="checkbox" name="gender" value="instagram" onClick="setAccount()"/></label>
</br>
</br>
<input type="submit" value="Submit" />
<br/><br/>
NOTE: Submit without selecting any account to see the validation message
</form>
Your e is null, because you use self executing function inside if and does not pass any event for it.
Try changing e.target to document.getElementById("linux-office-checkbox") or other not-checked element.
In jQuery I would check if any checkbox is selected by doing $('.checkboxClass:checked').length > 0

Get value from textbox based on checkbox on change event

I have two textboxes and one checkbox in a form.
I need to create a function javascript function for copy the first txtbox value to second textbox on checkbox change event.
I use the following code but its shows null on first time checkbox true.
function ShiptoBill()
{
var billing = document.getElementById("txtbilling").value;
var shipping = document.getElementById("txtshipping").value;
var check = // here i got checkbox checked or not
if(check == true)
{
// here I need to add the txtbilling value to txtshipping
}
}
Given that form controls can be accessed as named properties of the form, you can get a reference to the form from the checkbox, then conditionally set the value of txtshipping to the value of txtbilling depending on whether it's checked or not, e.g.:
<form>
<input name="txtbilling" value="foo"><br>
<input name="txtshipping" readonly><br>
<input name="sameas" type="checkbox" onclick="
this.form.txtshipping.value = this.checked? this.form.txtbilling.value : '';
"><br>
<input type="reset">
</form>
Of course you might want to set the listener dynamically, the above just provides a hint. You could also conditionally copy the contents over if the user changes them and the checkbox is checked, so a change event listener on txtbilling may be required too.
Try like following.
function ShiptoBill() {
var billing = document.getElementById("txtbilling");
var shipping = document.getElementById("txtshipping");
var check = document.getElementById("checkboxId").checked;
if (check == true) {
shipping.value = billing.value;
} else {
shipping.value = '';
}
}
<input type="text" id="txtbilling" />
<input type="text" id="txtshipping" />
<input type="checkbox" onchange="ShiptoBill()" id="checkboxId" />
function ShiptoBill()
{
var billing = document.getElementById("txtbilling");
var shipping = document.getElementById("txtshipping");
var check = document.getElementById("checkboxId").checked; // replace 'checkboxId' with your checkbox 'id'
if (check == true)
{
shipping.value = billing.value;
}
}
To get the event when it changes, do
$('#checkbox1').on('change',function() {
if($(this).checked) {
$('#input2').val($('#input1').val());
}
});
This checks for the checkbox to have a change, then checks if it is checked. If it is, it places the value of Input Box 1 into the value of Input Box 2.
EDIT: Here's a pure JS solution, and a JSBin too.
function ShiptoBill()
{
var billing = document.getElementById("txtbilling").value;
var shipping = document.getElementById("txtshipping").value;
var check = document.getElementById("thischeck").checked;
console.log(check);
if(check == true)
{
console.log('checked');
document.getElementById("txtshipping").value = billing;
} else {
console.log('not checked');
}
}
with
<input id="thischeck" type="checkbox" onclick="ShiptoBill()">

html.textbox javascript/jquery

I've the below ajax form. In the form I've got 2 textbox. There is a radio button to choose between Unlock and reset the password. All I want to do here is if I select unlock password label and textbox should disappear. I could do this with below javascript function only if the label and textbox were pure html. If I do that then Ajax doesnot pick up the value of password. Your help is much appreciated.
<input name="rblTooType" value="Unlock" type="radio" checked="checked" onclick="rblToolType_OnChange(true)" />Unlock
<input name="rblTooType" value="reset" type="radio" onclick="rblToolType_OnChange(false)" />reset Password
#using(Ajax.BeginForm("Search","User",new AjaxOptions {
UpdateTargetId = "divResults"
})){
#Html.Label("UserName")
#Html.TextBox("term")
#Html.Label("Password")
#Html.TextBox("Password")
<input id="btnSubmit" type="submit" value="Unlock"/>
}
<script type="text/javascript">
function rblToolType_OnChange(isUnlock) {
if (isUnlock) {
Password.style.display = "none";
btnSubmit.value = "Unlock";
}
else {
Password.style.display = "";
btnSubmit.value = "reset Password";
}
}
</script>
You seem to be depending on an old quirk of IE where element names and ids were added as global variables. It is bad practice to rely on that because other browsers don't support it (it was a very bad idea from the start). Reference your form elements correctly and it should work. e.g.
function rblToolType_OnChange(isUnlock) {
var form = document.forms['<form name>']
if (isUnlock) {
form.Password.style.display = "none";
form.btnSubmit.value = "Unlock";
}
else {
form.Password.style.display = "";
form.btnSubmit.value = "reset Password";
}
}

Categories