I have an input and table like this :
<td valign="top" style = "padding: 12px 0px 0px 30px;" >
<div class="form-group">
<label for="inputlg">Enter your favorite fruit :</label>
<input class="form-control input-lg" id="inputlg" type="text">
<table style="display: none;">
<tr>
<td> apple </td>
</tr>
<tr>
<td> mango </td>
</tr>
<tr>
<td> carrot </td>
</tr>
</table>
</div>
</td>
I want to unhide "apple" link when the user types "app" on input and unhide "mango" link when user types "man" and so on.. I have googled this problem but I couldn't find anything satisfying. What kind of JavaScript code do I need to achieve this? Thanks.
You could do something like this:
Start by mapping each row of the table in an object (where the key is the text content of the row and the value is the row itself) so that you can quickly access it later. Then add an event listener to the input and when the user types something in go through the object seeing if any of its properties match the value, using the object to show/hide the elements.
let element, elements, i, input, n, tableBody;
elements = {};
tableBody = document.getElementById(`table-body`);
for (i = tableBody.children.length - 1; i > -1; i--) {
element = tableBody.children[i];
elements[element.textContent.trim()] = element;
}
input = document.getElementById(`inputlg`);
input.addEventListener(`input`, filterElements);
function filterElements() {
let key, value;
value = input.value;
for (key in elements) {
if (key.match(value)) {
elements[key].classList.add(`show`);
} else {
elements[key].classList.remove(`show`);
}
}
}
#table-body >* {
display: none;
}
.show {
display: block !important;
}
<td valign="top" style = "padding: 12px 0px 0px 30px;" >
<div class="form-group">
<label for="inputlg">Enter your favorite fruit :</label>
<input class="form-control input-lg" id="inputlg" type="text">
<table>
<tbody id="table-body">
<tr>
<td>
apple
</td>
</tr>
<tr>
<td>
mango
</td>
</tr>
<tr>
<td>
carrot
</td>
</tr>
</tbody>
</table>
</div>
</td>
You can achieve this by writing little more code as below.
$("#inputlg").keyup(function() {
var value = $(this).val();
console.log(value);
if (value == 'app') {
$('.app').attr('style', 'display:block');
} else {
$('.app').attr('style', 'display:none');
}
if (value == 'mon') {
$('.mon').attr('style', 'display:block');
} else {
$('.mon').attr('style', 'display:none');
}
if (value == 'car') {
$('.car').attr('style', 'display:block');
} else {
$('.car').attr('style', 'display:none');
}
})
Note:- I have just added class in particular anchor tag for your help.
Adding code snippet for same.
<!--
To change this template, choose Tools | Templates
and open the template in the editor.
-->
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body>
<label for="inputlg">Enter your favorite fruit :</label>
<input class="form-control input-lg" id="inputlg" type="text">
<table >
<tr>
<td>
apple
</td>
</tr>
<tr >
<td>
mango
</td>
</tr>
<tr class="car" style="display:none">
<td>
carrot
</td>
</tr>
</table>
<script>
$(document).ready(function() {
$("#inputlg").keyup(function() {
var value = $(this).val();
console.log(value);
if (value == 'app') {
$('.app').attr('style', 'display:block');
} else {
$('.app').attr('style', 'display:none');
}
if (value == 'mon') {
$('.mon').attr('style', 'display:block');
} else {
$('.mon').attr('style', 'display:none');
}
if (value == 'car') {
$('.car').attr('style', 'display:block');
} else {
$('.car').attr('style', 'display:none');
}
})
})
</script>
</body>
</html>
Related
I tried a project which has a form to submit the employee expenses. I got everything working but unable to clear the form (entered details in the text fields) after clicking on submit.
Getting Error: (After entering the details and clicking the submit button)
Uncaught ReferenceError: d is not defined at HTMLInputElement.onclick (index.html:63:42)
Here is my code:
document.getElementById("submit").addEventListener("click", (e) => {
e.preventDefault();
// Form validation
function validate() {
if (document.myForm.empId.value == "") {
alert("Please provide your Employee ID!");
document.myForm.empId.focus();
return false;
}
if (document.myForm.empName.value == "") {
alert("Please provide your Name!");
document.myForm.empName.focus();
return false;
}
if (document.myForm.PaymentMode.value == "") {
alert("Select your Payment Mode!");
document.myForm.PaymentMode.focus();
return false;
}
if (document.myForm.Date.value == "") {
alert("Please provide the Date!");
document.myForm.Date.focus();
return false;
}
if (document.myForm.Bill.value == "") {
alert("Please provide your Bill Amount!");
document.myForm.Bill.focus();
return false;
}
return true;
}
let id = document.getElementById("id").innerText;
let empId = document.getElementById("empID").value;
let name = document.getElementById("name").innerText;
let empName = document.getElementById("empname").value;
let using = document.getElementById("using").innerText;
let mode = document.getElementById("payment-mode").value;
let day = document.getElementById("day").innerText;
let date = document.getElementById("date").value;
let amount = document.getElementById("amount").innerText;
let bill = document.getElementById("bill").value;
let form = document.getElementById("forReset");
let array = [
[id, empId],
[name, empName],
[using, mode],
[day, date],
[amount, bill],
];
let expenseList = Object.fromEntries(array);
const expenseTable = document.getElementById("expenseTable");
function output() {
if (validate()) {
for (let i = 0; i < Object.keys(expenseList).length; i++) {
expenseTable.innerHTML += `
<tr>
<td>${expenseList[id]}</td>
<td>${expenseList[name]}</td>
<td>${expenseList[using]}</td>
<td>${expenseList[day]}</td>
<td>$${expenseList[amount]}</td>
<td><a class="deleteButton">Delete</td>
</tr>
`;
for (let i = 0; i < expenseTable.children.length; i++) {
expenseTable.children[i]
.querySelector(".deleteButton")
.addEventListener("click", function () {
this.parentNode.parentNode.remove();
});
}
break;
}
} else {
return false;
}
}
output();
function d() {
form.reset();
}
d();
});
.table {
border: 1px solid black;
width: 100%;
}
th {
border-right: 1px solid black;
}
.table td {
border: 1px solid black;
text-align: center;
}
.deleteButton {
cursor: pointer;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Expense Tracker Project</title>
<link rel="stylesheet" href="./styles.css" />
</head>
<body>
<div class="employee-info">
<form
id="forReset"
class="expenesesForm"
name="myForm"
onsubmit="return(validate());"
method="POST"
action=""
>
<table>
<tr>
<td id="id">Employee ID:</td>
<td>
<input id="empID" name="empId" type="text" placeholder="Employee ID" />
</td>
</tr>
<tr>
<td id="name">Name:</td>
<td>
<input id="empname" type="text" placeholder="Name" name="empName" />
</td>
</tr>
<tr>
<td id="using">Payment Mode:</td>
<td>
<select id="payment-mode" name="PaymentMode">
<option class="" value="" selected disabled>
Select from the list
</option>
<option class="mode" value="card">Card</option>
<option class="mode" value="cheque">Cheque</option>
<option class="mode" value="cash">Cash</option>
<option class="mode" value="other">Other</option>
</select>
</td>
</tr>
<tr>
<td id="day">Date of Transaction:</td>
<td><input id="date" type="date" name="Date" /></td>
</tr>
<tr>
<td id="amount">Amount:</td>
<td><input id="bill" type="number" name="Bill" /></td>
</tr>
<tr>
<td>
<br />
<input
id="submit"
type="submit"
value="Submit"
onclick="javascript:d();"
/>
<input id="reset" type="reset" value="Cancel" />
</td>
</tr>
</table>
</form>
<br />
<table class="table">
<thead>
<tr>
<th>Employee Id</th>
<th>Name</th>
<th>Mode of Transaction</th>
<th>Date of Transaction</th>
<th>Amount</th>
</tr>
</thead>
<tbody id="expenseTable"></tbody>
</table>
</div>
<script src="./script.js"></script>
</body>
</html>
Expected output:
After clicking the submit button, entered form details should get cleared.
Here is a simple method,
click reset button automatically after submit
You could reuse the <input type="reset">
cancel icon to clear form values
https://www.w3schools.com/tags/att_input_type_reset.asp
Also, you can hide reset input using display:none, if it is not necessary in your screen
An alternative method is clear each input value by setting an empty value in it
function formReset () {
document.getElementById("empID").value = '';
document.getElementById("name").innerText = '';
document.getElementById("empname").value = '';
}
Here is a working example
document.getElementById("submit").addEventListener("click", (e) => {
e.preventDefault();
// Form validation
function validate() {
if (document.myForm.empId.value == "") {
alert("Please provide your Employee ID!");
document.myForm.empId.focus();
return false;
}
if (document.myForm.empName.value == "") {
alert("Please provide your Name!");
document.myForm.empName.focus();
return false;
}
if (document.myForm.PaymentMode.value == "") {
alert("Select your Payment Mode!");
document.myForm.PaymentMode.focus();
return false;
}
if (document.myForm.Date.value == "") {
alert("Please provide the Date!");
document.myForm.Date.focus();
return false;
}
if (document.myForm.Bill.value == "") {
alert("Please provide your Bill Amount!");
document.myForm.Bill.focus();
return false;
}
return true;
}
let id = document.getElementById("id").innerText;
let empId = document.getElementById("empID").value;
let name = document.getElementById("name").innerText;
let empName = document.getElementById("empname").value;
let using = document.getElementById("using").innerText;
let mode = document.getElementById("payment-mode").value;
let day = document.getElementById("day").innerText;
let date = document.getElementById("date").value;
let amount = document.getElementById("amount").innerText;
let bill = document.getElementById("bill").value;
let array = [
[id, empId],
[name, empName],
[using, mode],
[day, date],
[amount, bill],
];
let expenseList = Object.fromEntries(array);
const expenseTable = document.getElementById("expenseTable");
function output() {
if (validate()) {
for (let i = 0; i < Object.keys(expenseList).length; i++) {
expenseTable.innerHTML += `
<tr>
<td>${expenseList[id]}</td>
<td>${expenseList[name]}</td>
<td>${expenseList[using]}</td>
<td>${expenseList[day]}</td>
<td>$${expenseList[amount]}</td>
<td><a class="deleteButton">Delete</td>
</tr>
`;
for (let i = 0; i < expenseTable.children.length; i++) {
expenseTable.children[i]
.querySelector(".deleteButton")
.addEventListener("click", function () {
this.parentNode.parentNode.remove();
});
}
break;
}
} else {
return false;
}
}
output();
function clearData() {
document.getElementById("reset").click();
}
clearData();
});
.table {
border: 1px solid black;
width: 100%;
}
th {
border-right: 1px solid black;
}
.table td {
border: 1px solid black;
text-align: center;
}
.deleteButton {
cursor: pointer;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Expense Tracker Project</title>
<link rel="stylesheet" href="./styles.css" />
</head>
<body>
<div class="employee-info">
<form
id="forReset"
class="expenesesForm"
name="myForm"
onsubmit="return(validate());"
method="POST"
action=""
>
<table>
<tr>
<td id="id">Employee ID:</td>
<td>
<input id="empID" name="empId" type="text" placeholder="Employee ID" />
</td>
</tr>
<tr>
<td id="name">Name:</td>
<td>
<input id="empname" type="text" placeholder="Name" name="empName" />
</td>
</tr>
<tr>
<td id="using">Payment Mode:</td>
<td>
<select id="payment-mode" name="PaymentMode">
<option class="" value="" selected disabled>
Select from the list
</option>
<option class="mode" value="card">Card</option>
<option class="mode" value="cheque">Cheque</option>
<option class="mode" value="cash">Cash</option>
<option class="mode" value="other">Other</option>
</select>
</td>
</tr>
<tr>
<td id="day">Date of Transaction:</td>
<td><input id="date" type="date" name="Date" /></td>
</tr>
<tr>
<td id="amount">Amount:</td>
<td><input id="bill" type="number" name="Bill" /></td>
</tr>
<tr>
<td>
<br />
<input
id="submit"
type="submit"
value="Submit"
/>
<input id="reset" type="reset" value="Cancel" />
</td>
</tr>
</table>
</form>
<br />
<table class="table">
<thead>
<tr>
<th>Employee Id</th>
<th>Name</th>
<th>Mode of Transaction</th>
<th>Date of Transaction</th>
<th>Amount</th>
</tr>
</thead>
<tbody id="expenseTable"></tbody>
</table>
</div>
<script src="./script.js"></script>
</body>
</html>
function disableField()
{
var Count = $('#dataTable tr').length;
if (Count == 2){
$("input").not('.DeleteButton').prop('disabled', false);
}else{
$("input").prop('disabled', false);
}
}
//--------------------------------------------------
var regex = /^([a-zA-Z0-9 _-]+)$/;
var cindex = 0;
var quicklink = '' ;
$(document).on('click','.Buttons', function(addrow) {
var count = $('table tr:last input:text').filter((_,el) => el.value.trim() == "").length;
if(count || !$('.id_100 option[value=code]').attr('selected','selected')){
alert("Please fill the current row");
return false;
}
var $tr = $('#dataTable tbody tr:last');
var $clone = $tr.clone(true);
cindex++;
$clone.find(':input').not('select').not('.DeleteButton').val('').attr('disabled', true);
$clone.attr('id', 'id'+(cindex) ); //update row id if required
//update ids of elements in row
$clone.find("*").each(function() {
var id = this.id || "";
if(id != ""){
var match = id.match(regex) || [];
if (match.length == 2) {
this.id = this.name + (cindex);
}
}
});
$tr.after($clone);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table cellspacing="0" cellpadding="0" border="0" id="mainbox" class="mainbox"><tr><td>
<div class="toppanel"><ul><li></li></ul></div>
<div class="abcd"> <!--mainbox middlepanel start-->
<table cellspacing="0" cellpadding="0" border="0" id="maintable" class="maintable">
<tr>
<td valign="top">
<div id="pageheadingpanel">
<div id="pageheading">Quick Link Widget Configuration</div>
<div id="pageheadingdate"><xsl:call-template name="formatted_date"/></div>
</div>
</td>
</tr>
<tr>
<td height="100%" valign="top">
<div class="y_scroll" id="contentarea">
<div class="contentarea"><!--contentarea start-->
<span id="box" class="box"> <!--rounded curve/border start-->
<div class="middlepanel"> <!--contentarea box middlepanel start-->
<div style="display:block" id="textBox1" >
<span id="box1" class="box">
<div class="toppanel"><ul><li></li></ul></div>
<div class="middlepanel">
<table border="0" cellspacing="1" cellpadding="1" id="dataTable" name="dataTable" class="graphtable">
<thead>
<tr>
<td class="headingalign" width="16%">Links</td>
<td class="headingalign" width="32%">Desciption</td>
<td class="headingalign" width="16%">Image</td>
<td class="headingalign" width="16%">URL</td>
<td class="headingalign" width="05%"></td>
</tr>
</thead>
<tbody>
<tr id="id0" class="vals" name="id0">
<td>
<div class="id_100">
<select type="select-one" id='fldsearch' class="objselect" name="fldsearch" onChange="disableField()" >
<option value="">Select</option>
<xsl:for-each select="values from local db">
<xsl:sort order="ascending" select="description"/>
<option value="{description}">
<xsl:value-of select="description"/>
</option>
</xsl:for-each>
</select>
</div> </td>
<td>
<input id="flddesc" name="flddesc" maxlength="500" disabled="true" class="objinputtext1" size="85" value="{//RESPONSE}" />
</td>
<td>
<input id="fldimg" name="fldimg" maxlength="50" disabled="true" class="objinputtext2" size="35" value="{//RESPONSE}" />
</td>
<td>
<input id="fldurl" name="fldurl" maxlength="15" disabled="true" class="objinputtext3" size="35" value="{//RESPONSE}" />
</td>
<td>
<input tabindex="6" value="Delete Row" disabled="true" class="DeleteButton" type="button" />
</td>
</tr>
</tbody>
</table>
<div class="buttonarea">
<ul>
<li><input tabindex="6" id="Button3" value="Add New Row" class="Buttons" name="Button3" type="button" /></li>
</ul>
</div>
I have a table with a drop-down column in it. Whenever i change the values of drop-down my corresponding fields get enabled. The problem i am getting is if i change the values of my drop-down of previous row the columns of current row also get enabled.Any help will be appreciated. Thanks.
Edit:I have added 'Add Row' function too in my code.
I have added some changes in your disableField function. Pass parameter(this) disableField(this) in that function on chnage event.
function disableField(elem)
{
var Count = $('#dataTable tr').length;
if (Count == 2){
$(elem).closest('tr').find("input").not('.DeleteButton').prop('disabled', false);
}
else{
$(elem).closest('tr').find("input").prop('disabled', false);
}}
//--------------------------------------------------
var regex = /^([a-zA-Z0-9 _-]+)$/;
var cindex = 0;
var quicklink = '' ;
$(document).on('click','.Buttons', function(addrow) {
var count = $('table tr:last input:text').filter((_,el) => el.value.trim() == "").length;
if(count || !$('.id_100 option[value=code]').attr('selected','selected')){
alert("Please fill the current row");
return false;
}
var $tr = $('#dataTable tbody tr:last');
var $clone = $tr.clone(true);
cindex++;
$clone.find(':input').not('select').attr('disabled', true);
$clone.attr('id', 'id'+(cindex) ); //update row id if required
//update ids of elements in row
$clone.find("*").each(function() {
var id = this.id || "";
if(id != ""){
var match = id.match(regex) || [];
if (match.length == 2) {
this.id = this.name + (cindex);
}
}
});
$tr.after($clone);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table cellspacing="0" cellpadding="0" border="0" id="mainbox" class="mainbox"><tr><td>
<div class="toppanel"><ul><li></li></ul></div>
<div class="abcd"> <!--mainbox middlepanel start-->
<table cellspacing="0" cellpadding="0" border="0" id="maintable" class="maintable">
<tr>
<td valign="top">
<div id="pageheadingpanel">
<div id="pageheading">Quick Link Widget Configuration</div>
<div id="pageheadingdate"><xsl:call-template name="formatted_date"/></div>
</div>
</td>
</tr>
<tr>
<td height="100%" valign="top">
<div class="y_scroll" id="contentarea">
<div class="contentarea"><!--contentarea start-->
<span id="box" class="box"> <!--rounded curve/border start-->
<div class="middlepanel"> <!--contentarea box middlepanel start-->
<div style="display:block" id="textBox1" >
<span id="box1" class="box">
<div class="toppanel"><ul><li></li></ul></div>
<div class="middlepanel">
<table border="0" cellspacing="1" cellpadding="1" id="dataTable" name="dataTable" class="graphtable">
<thead>
<tr>
<td class="headingalign" width="16%">Links</td>
<td class="headingalign" width="32%">Desciption</td>
<td class="headingalign" width="16%">Image</td>
<td class="headingalign" width="16%">URL</td>
<td class="headingalign" width="05%"></td>
</tr>
</thead>
<tbody>
<tr id="id0" class="vals" name="id0">
<td>
<div class="id_100">
<select type="select-one" id='fldsearch' class="objselect" name="fldsearch" onChange="disableField(this)" >
<option value="">Select</option>
<xsl:for-each select="values from local db">
<xsl:sort order="ascending" select="description"/>
<option value="{description}">
<xsl:value-of select="description"/>
</option>
</xsl:for-each>
</select>
</div> </td>
<td>
<input id="flddesc" name="flddesc" maxlength="500" disabled="true" class="objinputtext1" size="85" value="{//RESPONSE}" />
</td>
<td>
<input id="fldimg" name="fldimg" maxlength="50" disabled="true" class="objinputtext2" size="35" value="{//RESPONSE}" />
</td>
<td>
<input id="fldurl" name="fldurl" maxlength="15" disabled="true" class="objinputtext3" size="35" value="{//RESPONSE}" />
</td>
<td>
<input tabindex="6" value="Delete Row" disabled="true" class="DeleteButton" type="button" />
</td>
</tr>
</tbody>
</table>
<div class="buttonarea">
<ul>
<li><input tabindex="6" id="Button3" value="Add New Row" class="Buttons" name="Button3" type="button" /></li>
</ul>
</div>
All in all there is to much extraneous code so the following answer has different code yet can be applied to the clunky code provided in question. I recommend that your code be more streamlined like the following demo provided in this answer.
Here's some suggestions:
If you are using multiple form controls (ex. <button>, <input>, <textarea>, <select>, etc), wrap everything into a <form>
If you have multiple tags (aka elements) that the user can click, submit, reset, change, input, etc register the events to the <form>
In order to find the exact form control that was clicked, changed, etc. use the Event.target property to find it or this keyword and the Event.data parameter.
$('form selector').on('event type', Event.data, callback function)
The #id and [name] attributes are unnecessary unless you are using certain Web APIs such as HTMLFormControlsCollection or HTMLFormElement
Never use event attributes (ex onchange="callback()") when using jQuery. Use the proper jQuery method or .on() method.
// jQuery method
$(selector).click(callback)
// .on() method
$(selector).on('click', callback)
Minor details:
The [type] attribute does not apply to the <select> tag.
Use <th> instead of <td> within <thead>
[maxlength] of 500 is ridiculous. Use <textarea> instead of <input>
Details are commented in demo
/*
Register form.io to the 'submit', 'click', and 'change' events
Note the callback function does not have `()` suffixed because it would be
interpreted as: "run function now"
The callback function doesn't run immediately it runs when a registered event is triggered.
*/
$('.io').on('submit click change', eventHandler);
// Define the counter
let counter = 0;
// Always pass the Event Object when defining a callback function
function eventHandler(event) {
// The Event Object has several properties...
// Get the type of event triggered (ie submit, change, or click)
let eType = event.type;
/*
Get the origin element of event
if 'submit' target will be <form>
if 'click' target will be <button>
if 'change' target will be <select>
*/
let eNode = event.target;
// Pass the event type through a switch() function...
switch (eType) {
// if type is 'submit'...
case 'submit':
// Create a deep clone of the first row
let clone = $('.grid tr:first-child').clone(true, true);
// Add clone as the last child of the <tbody>
$('.grid').append(clone);
// On .each() elment with class '.data' found within the clone...
clone.find('.data').each(function(i) {
// disable it
this.disabled = true;
// remove its value
this.value = '';
});
// Increment the counter by 1
counter++;
// Dereference the clone and assign id as row+counter
clone[0].id = `row${counter}`;
/*
Prevent default behavior:
Reset <form>
Send data to a server
*/
event.preventDefault();
// Stop event from bubbling any further up the event chain
event.stopPropagation();
// ...otherwise skip this case and continue onto the next case
break;
// if type is 'click'...
case 'click':
// if the clicked element (ie <button>) has class: '.del'...
if ($(eNode).hasClass('del')) {
// Get the clicked <button>'s ancestor <tr>
let row = $(eNode).closest('tr');
// if that <tr> is NOT the first <tr>...
if (row.index() !== 0) {
// remove the <tr>
row.remove();
}
}
event.stopPropagation();
break;
// if type is 'change'...
case 'change':
// if changed element (ie <select>) class is '.type'...
if ($(eNode).hasClass('type')) {
// Get the changed <select>'s ancestor <tr>
let row = $(eNode).closest('tr');
// if changed <select>'s value is NOT "X" return true otherwise return false
let pick = eNode.value !== "X" ? true : false;
/*
On .each() element with class .data within the <tr>
disable the .data if <select>'s value is "X"
Otherwise enable the .data
and then remove the .data value
*/
row.find('.data').each(function(i) {
this.disabled = !pick;
this.value = '';
});
}
event.stopPropagation();
break;
default:
event.stopPropagation();
break;
}
}
:root {
font: 400 3vw/1.2 Arial
}
form {
width: max-content;
margin: 10px auto
}
table {
table-layout: fixed;
border-collapse: separate;
border-spacing: 4px;
width: 90vw
}
th:first-of-type {
width: 20%
}
th:nth-of-type(2) {
width: 35%
}
th:nth-of-type(3) {
width: 35%
}
th:last-of-type {
width: 10%
}
td {
padding: 0 8px
}
select,
textarea,
button {
display: block;
min-width: 97%;
min-height: 1.2rem;
font-size: initial;
}
select {
padding: 2px 0 2px 2px
}
textarea {
resize: vertical;
overflow-y: auto;
overflow-x: hidden
}
<form class='io'>
<table>
<thead>
<tr>
<th>Type</th>
<th>Desciption</th>
<th>Image/URL</th>
<th><button>➕</button></th>
</tr>
</thead>
<tbody class='grid'>
<tr>
<td>
<select class='type'>
<option value="X" default></option>
<option value="GDS">Guides</option>
<option value="PRO">Promos</option>
<option value="TEM">Templates</option>
<option value="VID">Videos</option>
</select>
</td>
<td><textarea class='desc data' rows='1' cols='20' disabled></textarea></td>
<td><textarea class='urls data' rows='1' cols='20' disabled></textarea></td>
<td><button class='del' type='button'>❌</button></td>
</tr>
</tbody>
</table>
</form>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
I have following code to highlight table record with three different colors when user click a checkbox. How can I use a cookie to save the clicked value with grab the cookie every time the user opens the page everytime? I haven't no idea how cookies are used. Answer would be really appreciate
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>
<body>
<style>
.highlight-red {
background-color: red;
}
.highlight-green {
background-color: green;
}
.highlight-yellow {
background-color: yellow;
}
</style>
<div class="col-lg-10">
<table id="Table" border="1">
<tr class="highlight">
<td><input type="checkbox" name="cb1" id="cb1" value="y" onChange="changeSoma(this, 'red')" /></td>
<td>Click me</td>
</tr>
<tr>
<td><input type="checkbox" name="cb2" id="cb2" value="y" onChange="changeSoma(this, 'green')" /></td>
<td>Click me</td>
</tr>
<tr>
<td><input type="checkbox" name="cb3" id="cb3" value="y" onChange="changeSoma(this, 'yellow')" /></td>
<td>Click me</td>
</tr>
</table>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
function changeSoma(data, color){
if(data.checked && color == 'red'){
$(data).parent().parent().addClass("highlight-red");
}
else{
$(data).parent().parent().removeClass("highlight-red");
}
if(data.checked && color == 'green'){
$(data).parent().parent().addClass("highlight-green");
}
else{
$(data).parent().parent().removeClass("highlight-green");
}
if(data.checked && color == 'yellow'){
$(data).parent().parent().addClass("highlight-yellow");
}
else{
$(data).parent().parent().removeClass("highlight-yellow");
}
}
</script>
</body>
</html>
localStorage is easier than cookie I thought . You can set and get by localStorage.setItem or localStorage.getItem and it will remain until you remove them !!!
<script>
var cond = JSON.parse(localStorage.getItem("check"));
for(var i in cond) {
if(cond[i]) {
$("#"+i).attr("checked",true);
$("#"+i).parent().parent().addClass("highlight-"+cond[i]);
}
}
function changeSoma(data, color){
var state;
if(localStorage.getItem("check") == null) {
state = {cb1:0,cb2:0,cb3:0};
} else{
state = JSON.parse(localStorage.getItem("check"));
}
if(data.checked) {
$(data).parent().parent().addClass("highlight-"+color);
state[data.id]= color;
} else {
$(data).parent().parent().removeClass("highlight-"+color);
state[data.id]= 0;
}
localStorage.setItem("check",JSON.stringify(state));
}
</script>
it easier using localStorage but since you're using jQuery then use jQuery cookie plugin
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>
<body>
<style>
.highlight-red {
background-color: red;
}
.highlight-green {
background-color: green;
}
.highlight-yellow {
background-color: yellow;
}
</style>
<div class="col-lg-10">
<table id="Table" border="1">
<tr class="highlight">
<td><input type="checkbox" name="cb1" id="cb1" value="y" onChange="changeSoma(this, 'red')" /></td>
<td>Click me</td>
</tr>
<tr>
<td><input type="checkbox" name="cb2" id="cb2" value="y" onChange="changeSoma(this, 'green')" /></td>
<td>Click me</td>
</tr>
<tr>
<td><input type="checkbox" name="cb3" id="cb3" value="y" onChange="changeSoma(this, 'yellow')" /></td>
<td>Click me</td>
</tr>
</table>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/jquery.cookie/1.4.1/jquery.cookie.min.js"></script>
<script>
$(document).ready(function() {
var checkedBox = $.cookie('checkedBox');
console.log(checkedBox);
if(checkedBox !== undefined) {
// to check only
//$(checkedBox).attr('checked', true);
// emulate click to check and change the class
$(checkedBox).each(function() {
this.click();
})
}
})
function changeSoma(data, color) {
if(data.checked && color == 'red') {
$(data).parent().parent().addClass("highlight-red");
}
else {
$(data).parent().parent().removeClass("highlight-red");
}
if(data.checked && color == 'green') {
$(data).parent().parent().addClass("highlight-green");
}
else {
$(data).parent().parent().removeClass("highlight-green");
}
if(data.checked && color == 'yellow') {
$(data).parent().parent().addClass("highlight-yellow");
}
else {
$(data).parent().parent().removeClass("highlight-yellow");
}
// set cookie
var checked = "";
$('input[type="checkbox"]').each(function() {
if($(this).prop('checked')) {
checked += "#" + this.id + ","; // #cb, jQuery id selector
}
})
checked = checked.replace(/,$/, '')
console.log(checked);
$.cookie('checkedBox', checked);
}
</script>
</body>
</html>
I'm assuming you want the values to be selected still even when the user goes to a different page on your site and then select them again once back in that page.
As stated here, you set the cookies using the document.cookie javascript property.
The property mentioned above, however, is a semicolon separated key-value pair. you'll have to manipulate the string in order to add/edit a value.
Once you've added the value that you want, you can once again read it and then set the rows you want to be selected.
To get the selected value, you could use $(data).val() and put it inside changeSoma(). From there, you could check if it's checked $(data).is(':checked'). If it's checked, add it to document.cookie like document.cookie = "key=value; key2=value2;"
There are multiple checkboxes with same id, in asp.net repeater control. User can select either email or phone against each record in repeater rows.
In following example; there are two rows, if you select the email icon in first row then it ticks relavent checkbox which is fine but if you tick the email icon on the next row then it will untick the first row checkbox instead of ticking the one next to it.
$(function() {
$("[id*=divchkemail]").click(function() {
$(this).toggleClass("image-email");
if ($('#chkemail').prop('checked')) {
$("#chkemail").prop('checked', false);
} else {
if ($('#chkphone').prop('checked')) {
$("#chkphone").prop('checked', false);
$("#divchkphone").toggleClass("image-phone");
}
$("#chkemail").prop('checked', true);
}
});
$("[id*=divchkphone]").click(function() {
$(this).toggleClass("image-phone");
if ($('#chkphone').prop('checked')) {
$("#chkphone").prop('checked', false);
} else {
if ($('#chkemail').prop('checked')) {
$("#chkemail").prop('checked', false);
$("#divchkemail").toggleClass("image-email");
}
$("#chkphone").prop('checked', true);
}
});
});
.image-phone-disabled {
background-image: url('http://i.imgur.com/74FcgdS.png');
background-repeat: no-repeat;
width: 34px;
height: 34px;
}
.image-phone {
background-image: url(http://i.imgur.com/LwsHkOt.png);
background-repeat: no-repeat;
width: 34px;
height: 34px;
}
.image-email-disabled {
background-image: url('http://i.imgur.com/khd2NG8.png');
background-repeat: no-repeat;
width: 34px;
height: 34px;
}
.image-email {
background-image: url(http://i.imgur.com/y5KE9jx.png);
background-repeat: no-repeat;
width: 34px;
height: 34px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<table border=0>
<tr>
<td>
<div id="divchkemail" class="image-email-disabled" />
</td>
<td>
<input id="chkemail" type="checkbox" name="ctl00$ContentPlaceHolder1$tabContainer$tabRequests$Requests$cndt1$FindInspector$rptSearch$ctl01$chkemail"></input>
</td>
</tr>
<tr>
<td>
<div id="divchkphone" class="image-phone-disabled" />
</td>
<td>
<input id="chkphone" type="checkbox" name="ctl00$ContentPlaceHolder1$tabContainer$tabRequests$Requests$cndt1$FindInspector$rptSearch$ctl01$chkphone"></input>
</td>
</tr>
</table>
<br/>
<br/>
<br/>
<span>
</span>
<table border=0>
<tr>
<td>
<div id="divchkemail" class="image-email-disabled" />
</td>
<td>
<input id="chkemail" type="checkbox" name="ctl00$ContentPlaceHolder1$tabContainer$tabRequests$Requests$cndt1$FindInspector$rptSearch$ctl02$chkemail"></input>
</td>
</tr>
<tr>
<td>
<div id="divchkphone" class="image-phone-disabled" />
</td>
<td>
<input id="chkphone" type="checkbox" name="ctl00$ContentPlaceHolder1$tabContainer$tabRequests$Requests$cndt1$FindInspector$rptSearch$ctl02$chkphone"></input>
</td>
</tr>
</table>
<span>
</span>
JSFiddle
http://jsfiddle.net/g8Xuz/48/
although you must use unique id's for elements, given your scenario I've written down this fiddle.
i've used this $(this).parent().next('td').find('input:checkbox'); to find the checkboxes
please try this http://jsfiddle.net/g8Xuz/50/
This works.
I gave the rows a class of contact. It can also work without the class on the rows by using $("table > tr") instead. No need to know the exact class names and can handle any number of sets allowing the correct unique IDs for the fields.
FIDDLE
$(function () {
$(".contact").on("click", function (e) {
var $div = $(this).find("div"); // the div on the clicked row
var divClass = $div.prop("class"); // its class
var $checkbox = $(this).find("input"); // the checkbox
var check = $checkbox.is(":checked"); // whether or not it is checked
if (e.target.type != "checkbox") { // we clicked somewhere else
check = !check; // toggle
$checkbox.prop("checked", check); // set the check
}
if (check) { // are we enabling?
if (divClass.indexOf("disabled") != -1) { // disabled?
$div.removeClass(divClass).addClass(divClass.replace("-disabled", ""));
}
}
else { // disable it
$div.removeClass(divClass).addClass(divClass + "-disabled");
}
var $otherContact=$(this).siblings("tr"); // the sibling row
if (check) {
$div = $otherContact.find("div");
divClass=$div.prop("class");
if (divClass.indexOf("disabled") == -1) {
$div.removeClass(divClass).addClass(divClass+"-disabled");
}
$checkbox=$otherContact.find("input"); // the checkbox
if ($checkbox.is(":checked")) $checkbox.prop("checked",false);
}
});
});
It's happening because you are selecting element by id and which is duplicate. You have to find your required element traversing up through its ancestors in the DOM tree so that selector only select elements within current row by setting a area of elements. Here is working code.
$(function () {
$("[id*=divchkemail]").click(function (e) {
var currentRow = $(e.target).parents().closest('table');
$(this).toggleClass("image-email");
if ($(currentRow).find('#chkemail').prop('checked')) {
$(currentRow).find('#chkemail').prop('checked', false);
}
else {
var chkPhoneInCurrentRow = $(currentRow).find('#chkphone')
var divchkInCurrentRow = $(currentRow).find('#divchkphone')
if ($(chkPhoneInCurrentRow).prop('checked')) {
$(chkPhoneInCurrentRow).prop('checked', false);
$(divchkInCurrentRow).toggleClass("image-phone");
}
$(currentRow).find('#chkemail').prop('checked', true);
}
});
$("[id*=divchkphone]").click(function (e) {
var currentRow = $(e.target).parents().closest('table');
$(this).toggleClass("image-phone");
if ($(currentRow).find('#chkphone').prop('checked')) {
$(currentRow).find('#chkphone').prop('checked', false);
}
else {
var chkEmailInCurrentRow = $(currentRow).find('#chkemail')
var divchkInCurrentRow = $(currentRow).find('#divchkemail')
if ($(chkEmailInCurrentRow).prop('checked')) {
$(chkEmailInCurrentRow).prop('checked', false);
$(divchkInCurrentRow).toggleClass("image-email");
}
$(currentRow).find('#chkphone').prop('checked', true);
}
});
});
.image-phone-disabled {
background-image:url('http://i.imgur.com/74FcgdS.png');
background-repeat:no-repeat ;
width:34px;
height:34px;
}
.image-phone {
background-image:url(http://i.imgur.com/LwsHkOt.png);
background-repeat:no-repeat ;
width:34px;
height:34px;
}
.image-email-disabled {
background-image:url('http://i.imgur.com/khd2NG8.png');
background-repeat:no-repeat ;
width:34px;
height:34px;
}
.image-email {
background-image:url(http://i.imgur.com/y5KE9jx.png);
background-repeat:no-repeat ;
width:34px;
height:34px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<table border=0>
<tr>
<td>
<div id="divchkemail" class="image-email-disabled" /> </td>
<td> <input id="chkemail" type="checkbox" name="ctl00$ContentPlaceHolder1$tabContainer$tabRequests$Requests$cndt1$FindInspector$rptSearch$ctl01$chkemail"></input>
</td>
</tr>
<tr>
<td>
<div id="divchkphone" class="image-phone-disabled" />
</td>
<td>
<input id="chkphone" type="checkbox" name="ctl00$ContentPlaceHolder1$tabContainer$tabRequests$Requests$cndt1$FindInspector$rptSearch$ctl01$chkphone"></input>
</td>
</tr>
</table>
<br/>
<br/>
<br/>
<span>
</span>
<table border=0>
<tr>
<td><div id="divchkemail" class="image-email-disabled" /></td>
<td>
<input id="chkemail" type="checkbox" name="ctl00$ContentPlaceHolder1$tabContainer$tabRequests$Requests$cndt1$FindInspector$rptSearch$ctl02$chkemail"></input>
</td>
</tr>
<tr>
<td><div id="divchkphone" class="image-phone-disabled" /></td>
<td>
<input id="chkphone" type="checkbox" name="ctl00$ContentPlaceHolder1$tabContainer$tabRequests$Requests$cndt1$FindInspector$rptSearch$ctl02$chkphone"></input>
</td>
</tr>
</table>
<span>
</span>
Here is working fiddle.
http://jsfiddle.net/hannnan/noukkjsq/
This is happening because you are using the same IDs for everything - the JS cannot differentiate between the two rows. So you click the second row's icon, the first element it finds with your ID (#divchkemail) it performs the action on, which is in the first row.
I would like to be able to disable button click if the value entered in the text box below named "bidamt" is less then the Minimum Bid value below in the table. How do I go about doing this? I am trying to do this in JavaScript but it doesnt seem to pull the Minimum Bid value. Any help would be greatly appreciated.
#model IList<NucorPrototypes_V1.ViewModel.AuctionPage>
#{
ViewBag.Title = "MyBids";
}
<!doctype html>
<html>
<head>
<title>Auction </title>
<script type="text/javascript">
function checkBids(el) {
var bidInput = el.value
var MinBid = confirmbids.MinBid.value
if (el.value <= MinBid) {
document.getElementById("Bid").disabled = true;
}
else {
document.getElementById("Bid").disabled = false;
}
}
function RemoveBid(rb) {
if (typeof (rb) == "object") {
$(rb).closest("tr").remove();
}
}
</script>
#*<script type="text/javascript">
$('#bidamt').bind('keyup', function () {
if (Filled()) $('#btnSubmit').removeAttr('disabled');
});
function Filled() {
var filled = true;
$('body input').each(function () {
if ($(this).val() == '0') filled = false;
});
return filled;
}
*#
#*<script type="text/javascript">
//Validates that textbox value entered is a number or a number with a decimal
function checkDec(el) {
var typedBid = el.value
var min = confirmbids.MinBid.value
if (el.value <= confirmbids.MinBid.value) {
//alert("Invalid Bid Amount. Please enter a correct bid amount.");
document.getElementByName("Bid").disabled = true;
}
else {
document.getElementById("message").innerHTML = 'Your Bid is ' + el.value;
document.getElementByName("Bid").disabled = false;
}
}
*#
<body>
<div id="header" style="background-color: #008751">
<h1 style="margin-bottom: 0; color: #FFFFFF">Secondary Coil Auction</h1>
</div>
<br />
<div id="content">
<center>
<h4>In order to confirm bid you must enter a Bid Amount or Remove Bid before clicking Confirm.</h4>
#*Table that populates with bids the user selects. Here they can place a bid and remove a bid.*#
<form method="post" id="confirmbids" action="PlaceBid">
<table id="myTable1" border="2" style="background-color: #B0B0B0" cellpadding="10" class="table">
<tr>
<th>Bid Amount per 100 Weight</th>
<th>Remove Bid</th>
<th>Serial Number</th>
<th>Minimum Bid</th>
<th>Current High Bid</th>
<th>Grade</th>
<th>Heat Number</th>
<th>Gauge</th>
<th>Width</th>
<th>Weight</th>
<th>Defect 1</th>
<th>Defect 2</th>
<th>Defect 3</th>
</tr>
#foreach (var item in Model)
{
<tr>
<td>
<input type="text" #*pattern="[0-9]+([\.|,][0-9]+)?" step="0.01"*# name="bidamt" onkeyup="checkDec(this);" id="bidamt" />
</td>
<td>
<input type="button" value="Remove Bid" id="removeme" onclick="RemoveBid(this);"/>
</td>
<td>
<input type="text" style="background-color: #B0B0B0" readonly="true" name="coilID" value="#item.Coil_ID" />
</td>
<td>
<input type="text" style="background-color: #B0B0B0" readonly="true" name="MinBid" value="#item.Auc_MinBid" />
#*#Html.DisplayFor(modelItem => item.Auc_MinBid)*#
</td>
<td>
#Html.DisplayFor(modelItem => item.HighBid)
</td>
<td>
#Html.DisplayFor(modelItem => item.Coil_Grade)
</td>
<td>
#Html.DisplayFor(modelItem => item.Coil_HeatNo)
</td>
<td>
#Html.DisplayFor(modelItem => item.Coil_Gauge)
</td>
<td>
#Html.DisplayFor(modelItem => item.Coil_Width)
</td>
<td>
#Html.DisplayFor(modelItem => item.Coil_Weight, new { #id = "CoilWeight" })
</td>
<td>
#Html.DisplayFor(modelItem => item.Coil_Defect1)
</td>
<td>
#Html.DisplayFor(modelItem => item.Coil_Defect2)
</td>
<td>
#Html.DisplayFor(modelItem => item.Coil_Defect3)
</td>
</tr>
}
</table>
<center><input type="submit" name="Bid" id="Bid" onclick="checkBids(this)" value="Confirm Bids" />
</form>
<br />
</center>
</div>
<center>
<div class="well">
<div id="message"></div>
</div>
</center>
<br />
<br />
`
With jquery you can try this:
To use jquery you just embed
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
on the head tag of your html file. And put this on your click event.
$("#Bid").attr('disabled','disabled');
like this:
$("#Bid").click(function(){
if(something true){
$(this).attr('disabled','disabled');
}
});
You put your bidamt textbox in foreach loop and you set id="bidamt". So the problem is you can not set the same id many element, id is unique. The second problem is you called checkBids function on click event of button, so you can not get value of the button.