I have a problem where I have to show/hide multiple labels inside of the same td tag. Here is my JQuery code:
$j( document ).ready(function() {
var records = [];
var userID = 'here I am passing user ID'
~[tlist_sql;
SELECT ID1, User_ID, ID2
From RESERVATIONS
]
records.push({'idOne':"~(ID1)",'idTwo':"~(User_ID)",'idThree':"~(ID2)"});
[/tlist_sql]
for(var i=0; i< records.length; i++){
//here I am looking for matchin userID in my records array
if(records[i].idTwo == userID){
//If match, I want to hide input field and display name.
$j('#hide_' + records[i].idOne).parent('.hideEmail').hide().next('.showName').show();
}
//Here I'm looking if any of my records idThree has value 0
if(records[i].idThree == '0'){
//if match hide input and show word 'Reserved'
$j('#hide_' + records[i].idOne).parent('.hideEmail').hide().next('.showResreved').show();
}
}
});
Here is my html code:
<td>
<span class="hideEmail">
<input type="text" value="" id="hide_~(ID1)"/>
</span>
<label class="showName" style="display:none">
<span class="firstLast">Display Name</span>
</label>
<label class="showReserved" style="display:none">
<span class="notavailable">Reserved</span>
</label>
</td>
So problem show up once I combined both labels. At the first point I had only label with the class 'showName' and my logic worked fine. But once I added one more if statement in my JQuery and added another label with class 'showReserved' my code still displayed name label and class 'hideEmail' was hidden but class 'showReserved' never was displayed. Can anyone tell me why this does not work? Should I not combine two labels or something is wrong in my jquery?
Here is my working example: https://jsfiddle.net/dmilos89/nephebbv/2/
The problem its in this part:
$j('#hide_' + records[i].idOne).parent('.hideEmail').hide().next('.showResreved').show();
You typed "showReserved" wrong.
Here's a simple fix:
$j('#hide_' + records[i].idOne).parent('.hideEmail').hide().next('.showReserved').show();
Related
I have a form in which i have two checkboxes (Checkbox 1 and Checkbox 2).
Now, what i want is:
1.) If only Checkbox 1 is selected while adding the details then in edit mode only Checkbox 1 should be selected. (which is happening)
2.) If only Checkbox 2 is selected while adding the details then in edit mode only Checkbox 2 should be selected. (which is happening)
3.) If both of them were selected while adding the details then in edit mode both Checkboxes should be selected. (which is not happening)
If someone can point me in the right direction or point my mistake that would be really great.
I have already checked many solutions for this here but none of them works for me or you can point me towards the link which i may have missed.
I will add my jquery function as well as how i am storing them in database in comma separated way.
Checkboxes:-
<div class = "error_placement_checkbox">
<div align = "center" class="ui inverted form" id = "idcheckbox">
<div align = "center" class=" inline required fields">
<label> Checkboxes </label>
<div class="field">
<div class="ui checkbox">
<input type = "checkbox" name = "p_act1" value = "Checkbox_1" >
<label> Checkbox 1 </label>
</div>
</div>
<div class="field">
<div class="ui checkbox">
<input type = "checkbox" name = "p_act2" value = "Checkbox_2" >
<label> Checkbox 2 </label>
</div>
</div>
</div>
</div>
</div>
My jquery function:-
<script type="text/javascript">
$(document).ready(function()
{
$('input[type="checkbox"]').each(function(index)
{
if ($(this).val() == "<c:out value = '${product.p_act}' />")
($(this).prop('checked' , true));
});
});
</script>
In my Controller Servlet:- // To store them in comma separated.
List<String> items = new ArrayList<>();
if (request.getParameter("p_act1") != null) { items.add (request.getParameter("p_act1")); }
if (request.getParameter("p_act2") != null) { items.add (request.getParameter("p_act2")); }
String p_act = String.join(" , ", items);
Edit:-
This is my whole jquery function
<script type="text/javascript">
$(document).ready(function()
{
$('input[type="checkbox"]').each(function(index)
{
// console.log(this.value);
if ("<c:out value = '${product.p_act}' />".split(",").includes($(this).val()))
($(this).prop('checked' , true));
// console.log(this.value);
});
});
</script>
edit2:-
<script type="text/javascript">
$(document).ready(function()
{
$('input[type="checkbox"]').each(function(index)
{
console.log(this.value);
if ("11,22".split(",").includes($(this).val()))
($(this).prop('checked' , true));
console.log(this.value);
});
});
</script>
in console:-
(index):269 Checkbox_1
(index):272 Checkbox_1
(index):269 Checkbox_2
(index):272 Checkbox_2
When debugging js/jquery, always use rendered code - you'll see that you have something like:
if ($(this).val() == "123,456")
At no point, does either of your checkboxes have the value of "123,456"
So the if never works if you have both ticked as it's comparing a single value with a combined string. You could compare by using split and checking with includes:
if ("123,456".split(",").includes($(this).val())
So your code would be:
if ("<c:out value = '${product.p_act}' />".split(",").includes($(this).val())
Or you could pass them to the js as an array instead of multiple join/split.
The mandatory div id gets different numbers of inputs field displayed in it dynamically. Each input field starting from the first gets an id attr1, then attr2,..attr[n]. I need a way to get this into an array that gets the value of each input field with keyup and puts them into a separate input field with id detail.
This code works but returns undefined in some case when the hard coded input field ids exceed the generated input field ids. Thanks.
<div id="attributes"> <!--Start of Div Refreshed on Ajax Page Refresh-->
<div id="mandatory">
</div>
</div>
var total = '#attr1, #attr2';
$("#attributes").on('keyup', total, function(){
update();
})
function update() {
$("#detail").val($('#attr1').val() + "," $('#attr2').val());
}
If I understood right your question I think you're looking for something like that:
var fields = $("#mandatory").find("input"),
ids = [];
fields.each(function(){
$(this).on("keyup", function(){
var val = "";
ids = [];
fields.each(function(){
val += $(this).val() + (fields.length === ($(this).index() + 1) ? "": ", ");
ids.push($(this).get(0).id);
});
$("#detail").val(val);
console.log(ids)
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="attributes">
<div id="mandatory">
<input id="one" class="one" value="54"/>
<input id="two" class="two" value="55"/>
<input id="three" class="three" value="587"/>
</div>
</div>
<input id="detail" type="text" />
I'm not sure if this is what you're looking for, but I think it'll take you down the right path. In this example, any time a text input field is generated, an input event handler is attached to it that changes the value of a main textarea. If this isn't quite what you're looking for, please let me know and I'll be happy to try to work it out more.
document.getElementById('adder').onclick = function() {
var dynamicTextbox = document.createElement('input');
dynamicTextbox.setAttribute('type', 'text');
dynamicTextbox.setAttribute('class', 'dynamicText');
dynamicTextbox.addEventListener("input", function() {
var allTextboxes = document.getElementsByClassName('dynamicText');
var allValues = '';
for (var i=0; i < allTextboxes.length; i++) {
allValues += allTextboxes[i].value;
}
document.getElementById('detail').value = allValues;
});
document.getElementById('textboxes').appendChild(dynamicTextbox);
}
<textarea id="detail"></textarea>
<input id="adder" type="button" value="Add Text Field" />
<div id="textboxes"></div>
Clearing child div inside parent div, there are many answers like :
$(".ChildDiv").html("");
$('.ChildDiv > div').remove();
$(".ChildDiv").html("");
$("#ParentDiv").html("");
$(".ChildDiv div").remove();
$(".ChildDiv div").empty();
$('.ChildDiv ').find('div').remove();
Probably I have listed all possible way to remove the div's, but even after using all these, I still not able to clear all the div's inside Parent Div. let me explain what I am doing and what I need.
Scenario :
I have two container-1, one of the container has input search box, where I can search for entering employee name and select few employees Ex. 5 and can use "Add" button to move those employees to the other container-2 which is 'div'.
Now I click on report button event and get the information of those 5 people in different aspx, now if i go back to the page where i have to search for another 3 employees and when I again click on the "Add" button, it should add only 3 employees instead it is adding last searched 5 + 3 employees!!.
So i am trying to clear the 5 employees inside that div after i click on "Report" button , when i use alert() it says it has 0 element, but when I add it for the second time, it appends the data again, which i dont need. here is the code :
Points to remember :
1. ParentDiv is the container-2
2. ChildDiv is the child div inside ParentDiv(which is dynamically appended when we select 5 employees on "Add" button click"
Here is the code:
HTML :
<table id="topTable">
<tr>
<td id="leftpane">
<h4>Search for Employee by Name or Profile:</h4>
<input type="text" id="EmployeeSearchBox" class="search-box" aria-multiselectable="true" />
<select id="EmployeeList" size="20" multiple></select>
</td>
<td id="centerpane">
<div> <input type="button" value="Add >>" class="AddButton" id="buttonAdd" /></div>
<div> <input type="button" value="Add All >>" class="AddButton" id="buttonAddAll" /></div>
</td>
<td id="rightpane">
<h4>Selected Employees:</h4>
<div id="ParentDiv"></div>
</td>
</tr>
</table>
Run Report button event
<input class="data" type="submit" name="cmdSubmit" value="Run Report" onclick="return FormValidate();"
onserverclick="RunReport" runat="server" id="Submit1" />
Add Button Click :
which moves the employees from container-1 to container-2.
$(document).on('click', '#buttonAdd', function (e) {
$('#EmployeeList :selected').each(function (i, selected) {
myHash[$(selected).val()] = $(selected).text();
});
var myNode = $("#ParentDiv")[0];
while (myNode.firstChild) {
myNode.removeChild(myNode.firstChild);
}
for (var emp_id in myHash) {
var emp = $("#ParentDiv").append("<div class= ChildDiv id=" + emp_id + ">" + myHash[emp_id] + " <span class='close'>×</Span> </div>");
}
$('#EmployeeSearchBox').val("").trigger('input');
});
On click of "Report" button it should clear all the elements from ParentDiv/ChildDiv which is what I did, but still it is not clearing it, how can I resolve/remove these elements once "Report" button event clicked.
Here is a sample of "Report" button event :
function FormValidate() {//Part of my other code
$(".ChildDiv").html("");
$('.ChildDiv > div').remove();
$(".ChildDiv").html("");
$("#ParentDiv").html("");
$(".ChildDiv div").remove();
$(".ChildDiv div").empty();
$('.ChildDiv ').find('div').remove();
}
None of them is working, i feel there is an issue with the "Add" button event, where it is storing the data.
NOTE :
I don't want to clear the array of employee list, since I want to select multiple employees again again Ex. I can select 2 employees starts with the letter "M" and I can search the 2 employees of letter "L" and add those 2 employees, the container should hold 4 employees before "Report" button click.
Let me know if I am clear enough.
Console Log
Finally I could able to fix the issue, i was facing, I am posting the answer, now it is working as I need.
$(document).on('click', '#buttonAdd', function (e) {
var div_count = $('#ParentDiv').find('div').length;
if (div_count === 0) {
myHash = []; // Clearing the hash, so that it can add fresh employees, if count == 0 in container- 2.
$('#EmployeeList :selected').each(function (i, selected) {
myHash[$(selected).val()] = $(selected).text();
});
}
else { // If there are existing employees in container-2 then append few more.
$('#EmployeeList :selected').each(function (i, selected) {
myHash[$(selected).val()] = $(selected).text();
});
}
var myNode = $("#ParentDiv")[0];
console.log(myNode);
while (myNode.firstChild) {
myNode.removeChild(myNode.firstChild);
}
for (var emp_id in myHash) {
var emp = $("#ParentDiv").append("<div class= ChildDiv id=" + emp_id + ">" + myHash[emp_id] + " <span class='close'>×</Span> </div>");
}
$('#EmployeeSearchBox').val("").trigger('input');
});
What I did
Since I should be able to append multiple employees by searching, that is handled in 'else' part, if I generated the "Report" then, I am clearing the Container-2.
When I come back to page to search few more employees, by this time Container-2 will not be having any employees, so
var div_count = $('#ParentDiv').find('div').length;
if (div_count === 0) {
myHash = [];
//....
}
will clear the array which allow me to add fresh employees, hence it solved my problem :)
Thanks all for the support.
Edited to adjust on comments:
You need to clear the myHash variable. Otherwise employees will be added again from there.
I am trying to have a list of input checkboxes (which will be generated by PHP at a later time) but for now the content is static. So based off of the input, be able to select an employee, populates my div based on the selection and when unchecking the input, remove that same employee. I also need to be able to select multiple employees, instead of just one. Currently it updates the div with an employee but I cannot remove said employee. I can also only select one employee at a time (need to be able to click as many employees as needed all at once).
Here is what I got:
HTML
<div id="employee-list">
</div>
<div class="small-2 columns bord-right3 check-box">
<input type="checkbox" class="boxid" value="Joe Smith" name="employees">
<label class="checkbox-select">Select</label>
</div>
<div class="small-10 columns bord-right3">
<span class="employee-name">Joe Smith</span>
</div>
<div class="small-2 columns bord-right3 check-box">
<input type="checkbox" class="boxid" value="John Smith" name="employees">
<label class="checkbox-select">Select</label>
</div>
<div class="small-10 columns bord-right3">
<span class="employee-name">John Smith</span>
</div>
JS
$('input[name="employees"]').change(function () {
var inputVal = $('input[name="employees"]:checked').map(function () {
return this.value;
}).get();
console.log(inputVal);
if ($(this).prop('checked')) { //which checkbox was checked
if ($(this).val() == inputVal ) {
$("#employee-list").append('<span class="employee-name2_1">X ' + inputVal + '</span>');
}
} else {
$('.li_'+$(this).val()).remove();
console.log('item removed');
}
});
Any help is greatly appreciated! Please let me know if I have missed anything.
If I understand the goal correctly some of your code inside the change listener was unnecessary. You don't have to use map to get the value of the checkbox, $(this).val() is sufficient. From there a single if/else can add or remove the information as necessary.
Fiddle
$('input[name="employees"]').change(function () {
var inputVal = $(this).val();
var className = inputVal.replace(/ /g, '_');
if ($(this).prop('checked')) { //which checkbox was checked
$("#employee-list").append('<span class="span_' + className + '">X ' + inputVal + '</span>');
} else {
$('.span_'+className).remove();
console.log('item removed');
}
});
So I have a simple log in that requires a user to input values from a json file into two different text boxes ,when the user name and (in this case I have used ID as password) matches then an alert appears to say... "welcome"
After the .click function is carried out the users text still remains in the text box, how can I get both text boxes to appear blank after the .click function?
$(document).ready(function() {
//Hide alert when page loads
$("#loginalert").hide();
$("#invalid").hide();
$("#loginbtn").click(function(event){
$.getJSON('result.json', function(jd) {
var id = $('#userName').val();
var name = $('#userName2').val();
var valid = false;
for (var i=0; i<jd.user.length; i++) {
if ((jd.user[i].ID == id) && (jd.user[i].name == name)) {
valid=true;
$('#loginalert').html('<img src="' + jd.user[i].imgpath + '"><br><p> Welcome: ' + jd.user[i].name + '</p><button type="button" id="btnhide" class="btn btn-primary btn-md">Hide</button>');
//show the alert after loading the information
$("#loginalert").stop().fadeIn('slow').animate({ opacity: 1.0 }, 3000)
$('#invalid').hide();
$('#btnhide').on('click', function(e){
//console.log('here');
e.preventDefault();
$('#loginalert').hide();
});
}
}
if (!valid) {
$('#invalid').fadeIn('slow');
$('#loginalert').hide();
}
});
}); });
username 1 and #username 2 are the text boxes - is there any way to get user name 2 to display in stars ****** when the user enters the password - this question is not that necessary but if i could also get that working that would be good.
thanks guys hope someone can help :)
is there any way to get user name 2 to display in stars ****** when
the user enters the password
You can use an input box with text property set as password. But that password masking character will be . instead of *. Not exactly sure, whether it will be a different character in some browsers.
<input type="password" id="txtPassword" />
text box to appear blank after .click function
You can set the .val() property of the jQuery objects of two those two textboxes.
$('#userName, #username2').val('');
Use <input type="password"> to show typing as stars.
Clear inputs by setting their value to be empty: $('#userName').val('');
And perhaps consider breaking your code down into a couple smaller functions so it's easier to follow.
document.getElementById("#myTextbox").value="";
This should get your textbox and set the value of it to "", which is blank.
Edit: JSFiddle
Another Method:
You can also add the script directly inside the button without using/creating a function.
<input id="inputId" type="name" />
<button onclick="document.querySelector('#inputId').value='';"> Clear </button>
Using querySelector:
<input id="inputId" type="name" />
<button onclick="click()"> Clear </button>
<script>
function click() {
document.querySelector('#inputId').value="";
}
</script>