Hide element based on value of other elements - javascript

I am trying to hide a table based on the value of two fields, so that if field2 is equal to field1 the table is hidden.
JSfiddle
HTML:
<form>
Expected Number of Items: <input type="text" value="14" name="totalItems" id="totalItems">
<p>
Number of Items Entered: <input type="text" value="14" name="enteredItems" id="enteredItems">
</form>
<p>
<table border="1" style="width:100%" id="hideThis">
<tr>
<td>This should be hidden when "totalItems" equals "enteredItems"</td>
</tr>
</table>
JS:
function toggleClass(eid, myclass){
var theEle = document.getElementById(eid);
var eClass = theEle.className;
if(eClass.indexOf(myclass) >= 0){
theEle.className = eClass.replace(myclass, "");
}else{
theEle.className += "" +myclass;
}
}

See the comments in the code.
// Function to hide/show the table based on the values of inputs
function toggleTable() {
// Hides the table if the values of both input are same
$('#hideThis').toggle($('#totalItems').val() !== $('#enteredItems').val());
}
$(document).ready(function() {
// Bind the keyup event on both the inputs, call the function on event
$('#totalItems, #enteredItems').on('keyup', toggleTable).trigger('keyup');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<form>Expected Number of Items:
<input type="text" value="14" name="totalItems" id="totalItems">
<p>Number of Items Entered:
<input type="text" value="14" name="enteredItems" id="enteredItems">
</form>
<p>
<table border="1" style="width:100%" id="hideThis">
<tr>
<td>This should be hidden when "totalItems" equals "enteredItems"</td>
</tr>
</table>
jsfiddle Demo

$(document).ready( function() {
$('#totalItems, #enteredItems').keyup(function(){
if( $('#totalItems').val() == $('#enteredItems').val() ){
$('#hideThis').hide();
}else{
$('#hideThis').show();
}
});
});
If you need to check also at page load:
function checkFields(){
if( $('#totalItems').val() == $('#enteredItems').val() ){
$('#hideThis').hide();
}else{
$('#hideThis').show();
}
}
$(document).ready( function() {
$('#totalItems, #enteredItems').keyup(function(){
checkFields();
});
checkFields();
});
Plain JavaScript implementation:
function checkFields(){
if( document.getElementById('totalItems').value == document.getElementById('enteredItems').value ){
document.getElementById('hideThis').style.display = 'none';
}else{
document.getElementById('hideThis').style.display = 'inline-block';
}
}
document.getElementById('totalItems').addEventListener('keyup', function (){
checkFields();
}, false);
document.getElementById('enteredItems').addEventListener('keyup', function (){
checkFields();
}, false);
checkFields();

Here is the new JSFiddle
$(document).ready(function () {
var webpart_ID = 'hideThis';
var FieldA_id = 'totalItems';
var FieldB_id = 'enteredItems';
if ($('#' + FieldA_id).val() === $('#' + FieldB_id).val())
$('#' + webpart_ID).hide();
else
$('#' + webpart_ID).show();
});
This works.

You can bind a keyup events for both the text boxes, from where you can call a function to check if both the values are same..
compare();
$("#totalItems,#enteredItems").keyup(function() {
compare();
});
function compare() {
if ($("#totalItems").val() == $("#enteredItems").val()) {
$("#hideThis").hide();
} else {
$("#hideThis").show();
}
}
Fiddle

Related

jQuery stop script execution after if condition within click event

In this table, the rows are selectable only when Approved? column is empty. User can also add text in Deny Reason column.
When Deny button clicked, I want to make sure all deny reasons are filled in all selected rows before the rest of action can be executed. I tried to use return false , e.stopPropagation() , e.stopImmediatePropagation() and none of those works. As you can see in my example, alert("test") will always be executed. I want to stop that. Could you help?
$(function() {
var table = $("#myDataTable").DataTable({
info: false,
paging: false,
searching: false,
sorting: false
});
$("#myDataTable tbody").on('click', 'tr', function() {
var tr = $(this).closest("tr");
var rowText = tr.children("td").text();
var approveDeny = tr.children("td:nth-child(2)").text();
if (approveDeny == "") {
$(this).toggleClass('selected');
}
});
$("#myDataTable tbody tr td:nth-child(4)").click(function(e) {
if ($(this).prev().prev().text() == "") {
var text = $(this).text();
$(this).text('');
$('<textarea />').appendTo($(this)).val(text).select().blur(function() {
var newText = $(this).val();
var parentCell = $(this).parent();
parentCell.find('textarea').remove();
table.cell(parentCell).data(newText).draw();
});
}
e.stopPropagation();
});
$("#btnDeny").click(function(e) {
table.cells('.selected',3).every(function(rowIdx, tableLoop, rowLoop) {
var data = this.data();
if(data == "") {
alert( rowIdx + " is empty, you have to fill it.");
return false;
}
console.log(data);
});
alert("test");
});
});
<link href="https://cdn.datatables.net/1.10.10/css/jquery.dataTables.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.datatables.net/1.10.10/js/jquery.dataTables.min.js"></script>
<table id="myDataTable" class="table">
<thead>
<tr>
<th>Name</th>
<th>Approved?</th>
<th>Date</th>
<th>Deny Reason</th>
</tr>
</thead>
<tbody>
<tr id="1">
<td>Mickey Mouse</td>
<td>Yes</td>
<td>1/1/2016</td>
<td></td>
</tr>
<tr id="2">
<td>Minnie Mouse</td>
<td></td>
<td>1/3/2016</td>
<td></td>
</tr>
<tr id="3">
<td>Donald Duck</td>
<td></td>
<td>1/5/2016</td>
<td></td>
</tr>
</tbody>
</table>
<br/>
<div>
<input type="button" id="btnApprove" value="Approve">
<input type="button" id="btnDeny" value="Deny">
</div>
You can use a variable outside of the scope of your inner .every() function and change it within that function so you know if the data is valid or not.
$("#btnDeny").click(function(e) { // Outer scope function
var valid = true;
table.cells('.selected',3).every(function(rowIdx, tableLoop, rowLoop) { // inner scope function
var data = this.data();
if(data == "") {
valid = false;
alert( rowIdx + " is empty, you have to fill it.");
}
});
if (valid)
alert("Data valid");
});
Right, you need to assign the boolean output of every() to a variable, and then execute your alert only if that variable is true. Right now the result of the every() call is ignored, and the alert is executed regardless. Something like:
var isValid = table.cells('.selected',3).every(function(rowIdx, tableLoop, rowLoop) {
var data = this.data();
if(data == "") {
alert( rowIdx + " is empty, you have to fill it.");
return false;
}
console.log(data);
});
if (isValid) {
alert("test");
}

Change Text input value on checkbox select

I am trying to input the value of a checkbox into a text input.
Let's say that the input box is empty - you click on the checkbox, and the value assigned to the checbkox is being shown inside the input box.
$('input.lowercase').on('change', function(){
if ( $(this).is(':checked') ) {
$("input.qwer").on("keyup",function () {
$("input.qwer").html($(this).val());
}); } } );
No matter what I do I can't get this to work. Any help?
http://jsfiddle.net/6ycnzrty/
[EDITED] (As per your needs)
Demo on Fiddle
HTML:
<input type="text" class="output" value="" />
<br>
<input type="checkbox" class="qwer" value="qwerty">Input value of this checkbox(qwert)
<br>
<input type="checkbox" class="numbers" value="1234567890">Input value of this checkbox(numbers)
<br>
<input type="checkbox" class="asdfg" value="asdfg">Input value of this checkbox(asdfg)
<br>
<input type="checkbox" class="zxcvb" value="zxcvb">Input value of this checkbox(zxcvb)
JavaScript:
$('input.qwer').on('change', function () {
if ($(this).is(':checked')) {
$('.output').val($('.output').val() + $(this).val());
} else {
$('.output').val($('.output').val().replace($('.qwer').val(), ''));
}
});
$('input.numbers').on('change', function () {
if ($(this).is(':checked')) {
$('.output').val($('.output').val() + $(this).val());
} else {
$('.output').val($('.output').val().replace($('.numbers').val(), ''));
}
});
$('input.asdfg').on('change', function () {
if ($(this).is(':checked')) {
$('.output').val($('.output').val() + $(this).val());
} else {
$('.output').val($('.output').val().replace($('.asdfg').val(), ''));
}
});
$('input.zxcvb').on('change', function () {
if ($(this).is(':checked')) {
$('.output').val($('.output').val() + $(this).val());
} else {
$('.output').val($('.output').val().replace($('.zxcvb').val(), ''));
}
});
Try This :-
$('input.qwer').on('change', function(){
if ( $(this).is(':checked') ) {
$("input.output").val($(this).val());
}
else{ $("input.output").val("123"); }
});
With above code if checkbox is unchecked then textbox having class 'output' will get its initial view i.e '123',if you don't need this functionality then try this :
$('input.qwer').on('change', function(){
if ( $(this).is(':checked') ) {
$("input.output").val($(this).val());
}
});
EDIT :-
DEMO
Try
var $chk = $('input.qwer').on('change', function () {
//if the checkbox is checked and output is empty set the value
if (this.checked && !$output.val()) {
$output.val(this.value)
}
});
var $output = $("input.output").on("change", function () {
//when the value of output is changed as empty and checkbox is checked then set the value to checkbox
if (!this.value && $chk.is(':checked')) {
this.value = $chk.val();
}
});
Demo: Fiddle
$("input.qwer").on("change",function () {
if($(this).is(":checked"))
$("input.output").val($(this).val());
else
$("input.output").val("123");
});
DEMO

submit event is firing without checking validation or showing confirmation

My page is submitting straight away without checking for validation or displaying the alert. I believe the submit is firing early but is my issue that I have multiple forms?
My question is how can I get the submit to work as it should do where it checks the validation and if that is successful, display the confirmation?
I have had to post my whole code so that you can see the order of the code, because the order of the code maybe my downfall:
<script type="text/javascript">
$(document).ready(function () {
$('#sessionsDrop').change(function () {
$('#targetdiv').hide();
if ($(this).val() !== '') {
var text = $(this).find('option:selected').text();
var split = text.split(' - ');
$('#currentId').val($(this).find('option:selected').val());
$('#currentAssessment').val(split[0]);
$('#currentDate').val(split[1]);
$('#currentTime').val(split[2]);
} else {
$('#currentAssessment,#currentDate,#currentTime,#currentId').val('');
}
});
});
function validation(e) {
var isDataValid = true;
var moduleTextO = document.getElementById("modulesDrop");
var errModuleMsgO = document.getElementById("moduleAlert");
if (moduleTextO.value == "") {
$('#targetdiv').hide();
$('#assessmentForm').hide();
$('#choiceForm').hide();
$('#submitchoicebtn').hide();
errModuleMsgO.innerHTML = "Please Select a Module";
isDataValid = false;
} else {
errModuleMsgO.innerHTML = "";
}
if (isDataValid === false) {
if (e.preventDefault) {
e.preventDefault();
e.stopPropagation(); //VERY important
}
e.returnValue = false;
e.cancelBubble = true;
}
return isDataValid;
}
function choicevalidation() {
var isDataValid = true;
var currentAssesO = document.getElementById("currentAssessment");
var currentAssesMsgO = document.getElementById("currentAlert");
currentAssesMsgO.innerHTML = "";
if (currentAssesO.value == "") {
$('#targetdiv').hide();
currentAssesMsgO.innerHTML = "Please Select an Assessment to edit from the Assessment Drop Down Menu";
isDataValid = false;
} else {
currentAssesMsgO.innerHTML = "";
}
return isDataValid;
}
function showConfirm() {
var examInput = document.getElementById('curentAssessment').value;
var dateInput = document.getElementById('currentDate').value;
var timeInput = document.getElementById('currentTime').value;
if (choicevalidation()) {
var confirmMsg = confirm("Are you sure you want to take the following Assessment:" + "\n" + "Exam: " + examInput + "\n" + "Date: " + dateInput + "\n" + "Time: " + timeInput);
if (confirmMsg == true) {
submitform();
}
}
}
$('#choiceForm').on('submit', showConfirm);
</script>
<h1>TAKE AN ASSESSMENT</h1> //FORM 1
<form action="assessmentchoice.php" method="post" onsubmit="return validation(event);">
<table>
<tr>
<th>Module:
<select name="modules" id="modulesDrop">
<option value="">Please Select</option>
<option value="CHI2513_Systems Strategy_1">CHI2513 - Systems Strategy</option>
<option value="CHT2220_Interactive Systems_4">CHT2220 - Interactive Systems</option>
</select>
</th>
</tr>
</table>
<p>
<input id="moduleSubmit" type="submit" value="Submit Module" name="moduleSubmit"
/>
</p>
<div id="moduleAlert"></div>
<div id="targetdiv"></div>
</form>//FORM 2
<div id='lt-container'>
<form action='assessmentchoice.php' method='post' id='assessmentForm'>
<p id='warnings'></p>
<p><strong>Selected Module:</strong> CHI2513 - Systems Strategy
<input type='hidden'
value='1'>
</p>
<p><strong>Assessments:</strong>
<select name="session" id="sessionsDrop">
<option value="">Please Select</option>
<option value='28'>LDREW - 09-01-2013 - 09:00</option>
<option value='29'>BQNYF - 10-01-2013 - 10:00</option>
<option value='22' disabled>WDFRK - 17-01-2013 - 09:00</option>
<option value='26' disabled>POKUB1 - 25-01-2013 - 15:00</option>
</select>
</p>
</form>
</div>
<div id='rt-container'>//FORM 3 (This is where when submitted it should show confirmation)
<form
id='choiceForm' action='assessment.php' method='post'>
<p><strong>Chosen Assessment:</strong>
</p>
<table>
<tr>
<th></th>
<td>
<input type='hidden' id='currentId' name='Idcurrent' readonly='readonly'
value='' />
</td>
</tr>
<tr>
<th>Assessment:</th>
<td>
<input type='text' id='currentAssessment' name='Assessmentcurrent' readonly='readonly'
value='' />
</td>
</tr>
<tr>
<th>Date:</th>
<td>
<input type='text' id='currentDate' name='Datecurrent' readonly='readonly'
value='' />
</td>
</tr>
<tr>
<th>Start Time:</th>
<td>
<input type='text' id='currentTime' name='Timecurrent' readonly='readonly'
value='' />
</td>
</tr>
</table>
<div id='currentAlert'></div>
<p id='submitchoicebtn'>
<button id='choiceSubmit'>Choose Assessment</button>
</p>
</form>
here is a DEMO
try to change following line:
function showConfirm() { /* your existing code */ }
into
function showConfirm(e) {
e.preventDefault();
/* your existing code */
return false;
}
Have you already tried this:
function showConfirm(e) {
e.preventDefault();
var examInput = document.getElementById('curentAssessment').value;
var dateInput = document.getElementById('currentDate').value;
var timeInput = document.getElementById('currentTime').value;
if (choicevalidation()) {
return confirm("Are you sure you want to take the following Assessment:" + "\n" + "Exam: " + examInput + "\n" + "Date: " + dateInput + "\n" + "Time: " + timeInput);
}
return false;
}
$('#choiceSubmit').on('click', function(e) {
if (showConfirm(e)) {
$('#choiceForm').submit();
}
});
Your forms aren't nested so it shouldn't be because there are multiple.
Try removing all of the code in your validation function so that it only returns false:
function validation(e) {
return false;
}
If this works, you'll know the problem lies within your JavaScript and not the HTML. From there you can add back more and more of the function until you discover which part is causing the issue.
i think this line if ($(this).val() !== '') { should be like this if ($(this).val() != '') {
also as stated in another answers add this: e.preventDefault();
I would use the following code
$('#choiceSubmit').click(function(e) {
e.preventDefault();
var x = 0;
if (showConfirm(e)) {
$('#choiceForm').submit();
}
});
Have you used firebug or inspector (chrome/ie) and stepped through the javascript? In the above case, i'd add a breakpoint at the e.preventDefault() method. If it hits this, then the issue is within the javascript. if not then the javascript is not even bound to the submit button.

Set value of input

I'm trying to set the input value to 1 when checking the checkbox and empty when unchecking,
Can't get it to work, please help.
<td id="check-box"><input type="checkbox" name="checkbox"></td>
<td id="qty-box"><input type="text" name="qtybox"></td>
<script type="text/javascript">
function setValue(a) {
if (a < 1) {
a = 1;
}
}
var qty = $('#qty-box [name="qtybox"]').val();
$("#check-box").click(function() {
if ($(this[name = "checkbox"]).attr('checked', true)) {
setValue(qty);
}
else {
qty = 0;
}
});
</script>
Try the following -
<td id="check-box"><input type="checkbox" name="checkbox"></td>
<td id="qty-box"><input type="text" name="qtybox"></td>
<script type="text/javascript">
$(document).ready(function()
{
$("input[name='checkbox']").click(function()
{
if($(this).is(':checked'))
{
$("input[name='qtybox']").val("1");
}
else
{
$("input[name='qtybox']").val(""); // Change it to - val("0") -
//if you want to clear the text box with zero.
}
});
});
</script>
Here is a nice little demo of the working version.
Nice and short with a jsFiddle example:
$('input[name="checkbox"]').change(function(){
$('input[name="qtybox"]').val($(this).is(':checked')?'1':'');
})​
This will do
$(function(){
$('input[name="checkbox"]').click(function(){
$('input[name="qtybox"]').val(0);
if($(this).is(':checked'))
{
$('input[name="qtybox"]').val(1);
}
});
});
Working sample : http://jsfiddle.net/PBzuQ/17/
Give the id to the input makes thing much more simple.
<td><input type="checkbox" id="check-box" name="checkbox"></td>
<td><input type="text" id="qty-box" name="qtybox"></td>
<script type="text/javascript">
$(function () {
$("#check-box").click(function () {
var qty = $('#qty-box');
if ($(this).prop('checked')) {
if (qty.val() < 1) qty.val(1);
} else {
qty.val(0);
}
});
});
</script>

Javascript checkbox onChange

I have a checkbox in a form and I'd like it to work according to following scenario:
if someone checks it, the value of a textfield (totalCost) should be set to 10.
then, if I go back and uncheck it, a function calculate() sets the value of totalCost according to other parameters in the form.
So basically, I need the part where, when I check the checkbox I do one thing and when I uncheck it, I do another.
Pure javascript:
const checkbox = document.getElementById('myCheckbox')
checkbox.addEventListener('change', (event) => {
if (event.currentTarget.checked) {
alert('checked');
} else {
alert('not checked');
}
})
My Checkbox: <input id="myCheckbox" type="checkbox" />
function calc()
{
if (document.getElementById('xxx').checked)
{
document.getElementById('totalCost').value = 10;
} else {
calculate();
}
}
HTML
<input type="checkbox" id="xxx" name="xxx" onclick="calc();"/>
If you are using jQuery.. then I can suggest the following:
NOTE: I made some assumption here
$('#my_checkbox').click(function(){
if($(this).is(':checked')){
$('input[name="totalCost"]').val(10);
} else {
calculate();
}
});
Use an onclick event, because every click on a checkbox actually changes it.
The following solution makes use of jquery. Let's assume you have a checkbox with id of checkboxId.
const checkbox = $("#checkboxId");
checkbox.change(function(event) {
var checkbox = event.target;
if (checkbox.checked) {
//Checkbox has been checked
} else {
//Checkbox has been unchecked
}
});
HTML:
<input type="checkbox" onchange="handleChange(event)">
JS:
function handleChange(e) {
const {checked} = e.target;
}
Reference the checkbox by it's id and not with the #
Assign the function to the onclick attribute rather than using the change attribute
var checkbox = $("save_" + fieldName);
checkbox.onclick = function(event) {
var checkbox = event.target;
if (checkbox.checked) {
//Checkbox has been checked
} else {
//Checkbox has been unchecked
}
};
Javascript
// on toggle method
// to check status of checkbox
function onToggle() {
// check if checkbox is checked
if (document.querySelector('#my-checkbox').checked) {
// if checked
console.log('checked');
} else {
// if unchecked
console.log('unchecked');
}
}
HTML
<input id="my-checkbox" type="checkbox" onclick="onToggle()">
try
totalCost.value = checkbox.checked ? 10 : calculate();
function change(checkbox) {
totalCost.value = checkbox.checked ? 10 : calculate();
}
function calculate() {
return other.value*2;
}
input { display: block}
Checkbox: <input type="checkbox" onclick="change(this)"/>
Total cost: <input id="totalCost" type="number" value=5 />
Other: <input id="other" type="number" value=7 />
I know this seems like noob answer but I'm putting it here so that it can help others in the future.
Suppose you are building a table with a foreach loop. And at the same time adding checkboxes at the end.
<!-- Begin Loop-->
<tr>
<td><?=$criteria?></td>
<td><?=$indicator?></td>
<td><?=$target?></td>
<td>
<div class="form-check">
<input type="checkbox" class="form-check-input" name="active" value="<?=$id?>" <?=$status?'checked':''?>>
<!-- mark as 'checked' if checkbox was selected on a previous save -->
</div>
</td>
</tr>
<!-- End of Loop -->
You place a button below the table with a hidden input:
<form method="post" action="/goalobj-review" id="goalobj">
<!-- we retrieve saved checkboxes & concatenate them into a string separated by commas.i.e. $saved_data = "1,2,3"; -->
<input type="hidden" name="result" id="selected" value="<?= $saved_data ?>>
<button type="submit" class="btn btn-info" form="goalobj">Submit Changes</button>
</form>
You can write your script like so:
<script type="text/javascript">
var checkboxes = document.getElementsByClassName('form-check-input');
var i;
var tid = setInterval(function () {
if (document.readyState !== "complete") {
return;
}
clearInterval(tid);
for(i=0;i<checkboxes.length;i++){
checkboxes[i].addEventListener('click',checkBoxValue);
}
},100);
function checkBoxValue(event) {
var selected = document.querySelector("input[id=selected]");
var result = 0;
if(this.checked) {
if(selected.value.length > 0) {
result = selected.value + "," + this.value;
document.querySelector("input[id=selected]").value = result;
} else {
result = this.value;
document.querySelector("input[id=selected]").value = result;
}
}
if(! this.checked) {
// trigger if unchecked. if checkbox is marked as 'checked' from a previous saved is deselected, this will also remove its corresponding value from our hidden input.
var compact = selected.value.split(","); // split string into array
var index = compact.indexOf(this.value); // return index of our selected checkbox
compact.splice(index,1); // removes 1 item at specified index
var newValue = compact.join(",") // returns a new string
document.querySelector("input[id=selected]").value = newValue;
}
}
</script>
The ids of your checkboxes will be submitted as a string "1,2" within the result variable. You can then break it up at the controller level however you want.

Categories