control input field active status of form using toggle switch - javascript

Want the toggle switch to control the form fields when check, below is the sample code please suggest
<div class="form-group row">
<label for="lot-1" class="col-sm-2 col-form-label">x</label>
<div class="col-md-4">
<input type="text" class="form-control numbersOnly" name="lot-1" id="lot-1" placeholder="Result" min="4"
max="4">
<div class="toggleWrapper">
<input type="checkbox" name="toggle1" class="mobileToggle" id="toggleField" checked value="true"
data-id="lot-1">
<label for="toggle1"></label>
</div>
</div>
<div class="col-md-4">
<input type="text" class="form-control numbersOnly" name="lot-2" id="lot-2" placeholder="Result" min="4"
max="4">
<div class="toggleWrapper">
<input type="checkbox" name="toggle1" class="mobileToggle" id="toggleField" checked value="true"
data-id="lot-2">
<label for="toggle1"></label>
</div>
</div>
<div class="col-md-4">
<input type="text" class="form-control numbersOnly" name="lot-3" id="lot-3" placeholder="Result" min="4"
max="4">
</div>
<div class="toggleWrapper">
<input type="checkbox" name="toggle1" class="mobileToggle" id="toggleField" checked value="true" data-id="lot-3">
<label for="toggle1"></label>
</div>
</div>
And below is my jquery handler to make it functional
var fieldValue = false;
$('#toggleField').on('change', function(e) {
var fieldId = $("#toggleField").attr('data-id');
// console.log(fieldValue+fieldId);
if (fieldValue === true) {
// $("input[id=name]").attr('readonly',true);
$('#lot-'+fieldId).attr('readonly',true);
} else {
$('#lot-'+fieldId).attr('readonly',false);
}
});
I was testing to read the attribute data-id for each selected it will make the field disabled / read-only when unchecked by comparing the id with the data-id of respective input.

you can use the following code I changed the selector of change event $('#toggleField') to class name $('.mobileToggle') you have to remove Id attributes from checkboxes because it has the same id which is wrong
and get checked value dynamically to add and remove readonly attribute according to its value selector for inputs was wrong also $('#lot-'+fieldId) it has to be $('#'+fieldId) finally I fired change event manually to run it on first time page load you can add all this code inside document ready
$('.mobileToggle').on('change',function(e){
var fieldId = $(this).attr('data-id');
var fieldValue = $(this).is(':checked');
if(fieldValue == true){
$('#'+fieldId).attr('readonly', 'readonly');
}else{
$('#'+fieldId).removeAttr('readonly');
}
});
$('.mobileToggle').change();

Related

The checkbox function can only be used just on the first line in php

I have a modal and in this modal, I have a checkbox, The checkbox function can only be used on the first line table.
Code is like this, the checkbox function works but only on the first row of the table, henceforth the modal process doesn't work, I've tried adding
<?php echo $data['id_user']; ?>
to the ID but it still doesn't work.
<div class="form-group">
<label for="ubah_password">Ubah Password</label>
<div class="form-group">
<input type="checkbox" id="ubah_password" name="ubah_password" value="1">
<label class="prevent-select" for="ubah_password"> Ya, saya ingin mengubah password</label>
</div>
</div>
<div id="form_password" style="display: none;">
<div class="form-group">
<label for="editPassAdmin">Password Baru</label>
<input type="password" class="form-control form-control-sm" id="editPassAdmin" name="editPassAdmin" placeholder="Masukkan password baru">
</div>
<div class="form-group">
<label for="password_confirm">Konfirmasi Password</label>
<input type="password" class="form-control form-control-sm" id="password_confirm" name="password_confirm" placeholder="Masukkan kembali password baru">
</div>
</div>
<script>
var checkbox = document.getElementById("ubah_password");
var formPassword = document.getElementById("form_password");
checkbox.addEventListener("change", function() {
if (this.checked) {
formPassword.style.display = "block";
} else {
formPassword.style.display = "none";
}
});
</script>
The HTML ID attribute is designed to be unique, so even if you repeat it, you need to select them all, then individually in your JavaScript to load the modal.
Also, the name attributes should probably be unique enough for your form PHP code to tell which password you are changing.
For example, you could change the ID attributes to something like:
id="ubah_password[<?php echo $data['id_user']; ?>]"

Using jQuery's prop() to click on a checkbox isn't running the onClick() function set on the checkbox

I have two checkboxes that has a onclick() function assigned to them. Now in a button, I have jquery set so that the checkboxes are checked automatically, via prop()
When the button is pressed, the checkboxes are checked but the onclick() function isn't working. How do I make it work? Any idea?
html:
<div class="container">
<h2 class="mt-5">Tester</h2>
<form>
<div class="form-group row align-items-center">
<div class="col-3">
<label for="policyinInt">Int</label>
<input class="form-control" value="0" readonly="readonly" type="text" name="total" />
</div>
<div class="col-3">
<label for="policyinHex">Hex</label>
<input class="form-control" value="0" readonly="readonly" type="text" name="totalhex" id="policyinHex" />
</div>
</div>
</form>
<input class="form-check-input" name="values" value="256" type="checkbox" onclick="totalIt()" id="bit8" /> <span class="code">0x00000100</span><br>
<input class="form-check-input" name="values" value="512" type="checkbox" onclick="totalIt()" id="bit9" /> <span class="code">0x00000200</span> <br>
<button type="button" class="default btn btn-outline-primary">Check the boxes</button>
<br>
</div>
javascript:
function totalIt() {
var input = document.getElementsByName("values");
var total = 0;
for (var i = 0; i < input.length; i++) {
if (input[i].checked) {
total += parseInt(input[i].value);
}
}
document.getElementsByName("total")[0].value = total;
document.getElementsByName("totalhex")[0].value = decimalToHexString(total);
}
function decimalToHexString(number)
{
number = number.toString(16).toUpperCase()
number = "0x"+number;
return number;
}
$(document).ready(function(){
$(".default").click(function(){
$("#bit8").prop("checked", true);
$("#bit9").prop("checked", true);
});
});
jsfiddle of what I have so far: https://jsfiddle.net/fahims/7eyf5v86/
So when the checkboxes are checked manually, the function is working. But when the button is used to trigger the checkbox, the functions arent working. Is there a better way to do what I'm trying to achieve?
Just call totalIt() after you set the checked properties. Setting properties or values programmatically does not trigger user events
$(".default").click(function(){
$("#bit8, #bit9").prop("checked", true);
totalIt();
});

how to make these two components appear on the same line? (textbox label and the textbox)

this is my html file
<div id="radioHeader">
<div id="radioHeader" onclick="radioClicked()">
<div class="radio form-check form-check-inline component"> Mode of Transaction<span
style="color:red;">*</span>
<div class="radiogq">
<input type="radio" name="mode" value="cheque" onclick="" checked> Cheque
<input type="radio" name="mode" value="bank"> Bank Transaction
</div>
</div>
<div>
<p id="idc"></p><input class="textb" type="text" id="fname" class="col-form-label input" placeholder="Registration Id"
name="fname" size="100">
</div>
</div>
</div>
this is my js file from where I am adding the value in the textbox, and I want them to be in the same line.
this textbox label will chance as per the change in the radio button
function radioClicked() {
let shapeChoice = document.querySelector('input[name="mode"]:checked').value;
switch (shapeChoice) {
case 'cheque':
document.getElementById("idc").innerHTML = "Enter your Cheque Id"
break;
case 'bank':
document.getElementById("idc").innerHTML = "Enter your Transaction Id"
break;
default:
doucment.getElementById("idc").innerHTML = "Default"
}
};
radioClicked();
Use CSS, one of the ways is float:left
function radioClicked() {
let shapeChoice = document.querySelector('input[name="mode"]:checked').value;
switch (shapeChoice) {
case 'cheque':
document.getElementById("idc").innerHTML = "Enter your Cheque Id"
break;
case 'bank':
document.getElementById("idc").innerHTML = "Enter your Transaction Id"
break;
default:
doucment.getElementById("idc").innerHTML = "Default"
}
};
radioClicked();
.cs1 {
float:left;
}
<div id="radioHeader">
<div class="radio form-check form-check-inline component" "> Mode of Transaction<span
style="color:red;">*</span></div>
<div id="radioHeader" onclick="radioClicked()">
<div class="cs1 radiogq">
<input type="radio" name="mode" value="cheque" onclick="" checked> Cheque
<input type="radio" name="mode" value="bank"> Bank Transaction
</div>
</div>
<div class='cs1'> </div>
<div class='cs1' style="position:relative;top:2px;" id=idc></div>
<div class='cs1'> </div>
<div class='cs1'>
<input class="textb" type="text" id="fname" class="col-form-label input" placeholder="Registration Id"
name="fname" style="width:200px;max-width:100%:">
</div>
</div>
I've added a few improvements to your script and made sure your idc element floats left. This makes sure that the next element will appear next to it. To make it look better, I also added some margins to the input box.
Keep in mind that it may look like it doesn't work properly here on Stack Overflow as the window for the example is pretty small. But it'll work fine in your browser.
// Make sure it runs after the page is loaded
document.addEventListener("DOMContentLoaded", function(e){
// Get all radio buttons where name equals "mode"
const radios = document.querySelectorAll('input[type=radio][name="mode"]');
function radioChangeHandler(event){
const idc = document.getElementById("idc");
if(this.value === "cheque"){
idc.innerText = "Enter your Cheque Id";
} else if(this.value === "bank"){
idc.innerText = "Enter your Transaction Id";
} else {
idc.innerText = "Default";
}
}
// Attach event handler to each radio button
Array.prototype.forEach.call(radios, function(radio) {
radio.addEventListener('change', radioChangeHandler);
});
});
#idc {
float: left;
}
#fname {
margin-top: 13px;
margin-left: 5px;
}
<div id="radioHeader">
<div id="radioHeader">
<div class="radio form-check form-check-inline component"> Mode of Transaction<span style="color:red;">*</span>
<div class="radiogq">
<input type="radio" name="mode" value="cheque" onclick="" checked> Cheque
<input type="radio" name="mode" value="bank"> Bank Transaction
</div>
</div>
<div>
<p id="idc"></p><input class="textb" type="text" id="fname" class="col-form-label input" placeholder="Registration Id" name="fname" size="100">
</div>
</div>
</div>
Reference for the radio event handler: How to use radio on change event?
The behavior is because the paragraph i.e. element by default is block element. So, it occupies a block and adds line break before and after it. So, one way of changing it would be to change the behavior of paragraph block i.e. element by changing the display property to inline or inline block. Since it already has any id of idc, it can be done as :-
#idc {
display: inline;
}
Alternatively, the label and input can be placed inside the paragraph and it will display in the same line given there is enough to accommodate the element. This is the better approach since, a label tag is used for displaying the label and is linked to the input with for attribute.
<p>
<label id="idc" for="fname"></label>
<input class="textb" type="text" id="fname" class="col-form-label input" placeholder="Registration Id" name="fname" size="100">
</p>

foreach loop, make the next input field required

I made a function, which should check whether my input field, with type checkbox has been checked or not... but whenever I check my input field the input fields I wish to make required do not get the required attributes.
I basically tried everything from this topic: jQuery add required to input fields
and read this topic in hopes of finding something: .prop() vs .attr()
but unfortunately none of the topics has helped me much further. So either I made a mistake somewhere in my code, or the required attribute is a bit buggy.
I call the function via my input field (onclick event).
I have already checked whether selectors were correct, and they are.
this is how my HTML looks like:
<div class="row" style="margin: auto;">
<div class="custom-control custom-checkbox col-md-4">
<input class="custom-control-input" onclick="is_required()" type="checkbox" id="fruittariër" value="fruittariër" name="vegetarisch[]">
<label class="custom-control-label" for="fruittariër"> fruittariër</label>
</div>
<div class="col-md-4 input-group leftVeganPadding">
<div class="input-group-prepend">
<span class="input-group-text" id="basic-addon1">€</span>
</div>
<input type="number" step="0.01" class="form-control" placeholder="Kosten" name="vegCosts[]">
</div>
<div class="input-group col-md-4 leftVeganPadding">
<div class="input-group-prepend">
<span class="input-group-text" id="veganDatePicker"><i class="fas fa-calendar-alt"></i></span>
</div>
<input type="text" class="form-control" name="veganEindDatum[]" id="shutDateFruittariër" placeholder="Sluit Datum" aria-label="veganDatePicker" aria-describedby="veganDatePicker">
</div>
</div>
this is how I call my function:
<input class="custom-control-input" onclick="is_required()" type="checkbox" value="vegan" name="vegetarisch[]">
function is_required() {
//check whether the checkbox has been checked or not
//if yes, make the other input fields inside the row required
// variable odin = the row wrapped around the cols
$('input[name="vegetarisch[]"]').each(function(index, thisElement) {
if($(thisElement).is(':checked')) {
let odin = $(thisElement).closest('.row');
odin.find('input[name="vegCosts[]"]').attr('required', true);
odin.find('input[name="veganEindDatum[]"]').attr('required', true);
} else {
odin = $(thisElement).closest('.row');
odin.find('input[name="vegCosts[]"]').attr('required', false);
odin.find('input[name="veganEindDatum[]"]').attr('required', false);
}
});
}
So what I wish to achieve: When the checkbox is checked I want to have the 2 other input fields inside the row to gain the attribute 'required'.
No need for an each you can pretty much do this in one line with an event handler.
Below, the closest .row is found for the button that was clicked. Then one selector is used to find both inputs that will be required. Then the required prop is set based on the status of the check button.
$(document).ready(function() {
//Handle events on the checkbox
$('input[name="vegetarisch[]"]').on('click', function() {
//get the nearst row
$(this).closest('.row')
//Find the check boxes
.find('input[name="vegCosts[]"],input[name="veganEindDatum[]"]')
//set the required propery if the checkbox is checked
.prop('required', $(this).is(":checked"));
});
});
:required {
border-color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<div class="row" style="margin: auto;">
<div class="custom-control custom-checkbox col-md-4">
<input class="custom-control-input" type="checkbox" id="fruittariër" value="fruittariër" name="vegetarisch[]">
<label class="custom-control-label" for="fruittariër"> fruittariër</label>
</div>
<div class="col-md-4 input-group leftVeganPadding">
<div class="input-group-prepend">
<span class="input-group-text" id="basic-addon1">€</span>
</div>
<input type="number" step="0.01" class="form-control" placeholder="Kosten" name="vegCosts[]">
</div>
<div class="input-group col-md-4 leftVeganPadding">
<div class="input-group-prepend">
<span class="input-group-text" id="veganDatePicker"><i class="fas fa-calendar-alt"></i></span>
</div>
<input type="text" class="form-control" name="veganEindDatum[]" id="shutDateFruittariër" placeholder="Sluit Datum" aria-label="veganDatePicker" aria-describedby="veganDatePicker">
</div>
</div>
You may want to try using the onchange event:
<input class="custom-control-input" id="myCheckbox" type="checkbox" value="vegan" name="vegetarisch[]">
$('#myCheckbox').change(function () {
is_required();
});
function is_required() {
let odin = $(thisElement).closest('.row');
$('input[name="vegetarisch[]"]').each(function (index, thisElement) {
if ($(thisElement).is(':checked')) {
odin.find('input[name="vegCosts[]"]').attr('required', true);
odin.find('input[name="veganEindDatum[]"]').attr('required', true);
} else {
odin.find('input[name="vegCosts[]"]').attr('required', false);
odin.find('input[name="veganEindDatum[]"]').attr('required', false);
}
});
}

Change input form when checkbox is pressed

I would like to create a webform which gives users the opportunity to create tickets more easily.
In this webform I have two input forms and a checkbox:
What I would like to have is the following (created via PowerPoint):
So if the users click the checkbox the webform should automatically disable the second input form and copy the value and/or the placeholder of the first input form. So briefly speaking: If the users click the checkbox the second input form should be exactly like the first one, except that it is disabled.
Unfortunately I have no clue how to do this. By now my code looks like this:
Input field 1 (key user) + checkbox:
<div class="form-group">
<label class="control-label col-sm-2" for="keyuser">Key-User:</label>
<div class="col-sm-10">
<input type="keyuser" class="form-control" id="keyuser" placeholder="Username Key-User">
<div class="checkbox">
<label onclick="checkbox()">
<input type="checkbox">
</label>Is the affected user
</div>
</div>
Input field 2 (affected user):
<div class="form-group">
<label class="control-label col-sm-2" for="affuser">Affected User:</label>
<div class="col-sm-10">
<input type="affuser" class="form-control" id="affuser" placeholder="Username affected user">
</div>
Checkbox() [it does not work at all right now]:
function checkbox() {
"use strict";
if (check === "False") {
check = "True";
$('#affuser').attr('placeholder', 'Username Key-User');
} else {
check = "False";
$('#affuser').attr('placeholder', 'Username affected user');
}
}
How can I implement the functions mentioned above?
There are some changes that I would want to implement to your script rightaway:
Do not use inline JS. Instead, create an onchange event handler for the checkbox (not the label element)
Use IDs for your checkbox so that your <label> will be functioanlly attached to it.
For the JS, it's quite simple: When an onchange event is registered on the checkbox element, evaluate if it is checked or not, by simply evaluating the .is(':checked') boolean:
If checked:
disable the #affuser element using .prop('disabled', true)
update the placeholder attribute using .attr('placeholder', ...)
If unchecked:
enable the aforementioned element using .prop('disabled', false)
update the placeholder attribute using, again, .attr('placeholder', ...)
$(function() {
$('#checkbox1').on('change', function() {
if($(this).is(':checked')) {
$('#affuser')
.prop('disabled', true)
.attr('placeholder', $('#keyuser').attr('placeholder'));
} else {
$('#affuser')
.prop('disabled', false)
.attr('placeholder', 'Username affected user');
}
});
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-alpha.6/css/bootstrap.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group">
<label class="control-label col-sm-2" for="keyuser">Key-User:</label>
<div class="col-sm-10">
<input type="keyuser" class="form-control" id="keyuser" placeholder="Username Key-User">
<div class="checkbox">
<label for="checkbox1">
<input type="checkbox" id="checkbox1">
</label>Is the affected user
</div>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="affuser">Affected User:</label>
<div class="col-sm-10">
<input type="affuser" class="form-control" id="affuser" placeholder="Username affected user">
</div>
</div>

Categories

Resources