How to get the id value from check box? - javascript

1 naga naga123
2 Tamil tamil123
3 vinod vinod123
4 naveen naveen123
5 jakkir jakkir123
save edit delete
UserID:
UserName:
Password:
I have check box at the end of each row. When I click the check box and select edit the values should get displayed in the text boxes corresponding to userId, userName & Password.
My js code for edit is
function Edit(){
var i=dwr.util.getValue("userId");
LoginManagement.selectId(i,function(login){
dwr.util.setValues({userId:userId, userName:login.userName,
passWord:login.passWord});
});
}
My js code for checkbox is
function Intialize(){
LoginManagement.getLoginDetails(function(loginList){
var x = "";
for(var i=0; i<loginList.length; i++){
var login =loginList[i];
x += "<tr><td>"+login.userId+"</td><td>"+login.userName+"</td><td>"+login.passWord+"</td><td><input type = 'checkbox' id = 'cbid"+login.userId+"'</td></tr>";
}
$("#loginTable").html(x);
});
}
How should i get the id value in edit so that if i click the button it should display the values corresponding. Any suggestion please?

Hope I understand you correctly.
Remove Edit() from onclick of edit link and continue the Initialize function as follows:
...
$("#loginTable").html(x);
ids = ['userId', 'userName', 'Password']; // Ids of text boxes to be populated
$("#editlink").click(function(){ // Assuming edit link has id="editlink"
var tds = $("#loginTable").find("input:checked[type=checkbox]").parent().siblings();
for(var i = 0; i < ids.length; i++){
$('#' + ids[i]).html($(tds[i]).html());
}
Edit(); // Better copy the code of Edit() directly in here
return false; // Prevent default click action (go to href)
});
});
If this is wrong please post the complete HTML as well.

the id can be retrieved by using the attr var idvalue = $("input:last").attr("id"); but you have to get reference to the checkbox in your scenario .. if you have a css class name associated with it use that like $(.classname) and then use the attr to get the value.

Related

How to add multiple input field inside a div dynamically using JavaScript/jQuery?

I need to create some multiple input field dynamically on onkeypress event using JavaScript/jQuery.
I have one text-box,when user is entering any key on that text area two input field and second text-box is opening. When user will enter any key on second text box again another two input field and third text-box will open and so on. There is also a cross button is creating to close each individual set of text-box. In my current code I doing this putting all field static as user may create many numbers of input field so that I want to create those in dynamically with different name and id.
My code is in this Plunkr.
EDIT: Misunderstood question, answer below
This can easily be done if you have a specific field in which to create the input fields. For example, I will load input fields into document.body
Everytime you call newinput() an input field is created in parent who's id starts at input0 and increments each time
var id = 0;
var newinput = function() {
var parent = document.body
var field = document.createElement("input")
field.className = "myclassname"
field.style = "display:block;"
field.id = "input" + id;
parent.appendChild(field);
id += 1;
}
<body>
<div>Click plus to add input</div>
<button type="button" name="button" onclick="newinput()">+</button>
</body>
In your case, it looks like you want to add a group, you can do this:
var fieldgroup = document.querySelector(".questionshowp .form-group").cloneNode(true); // (1)
var addinput = function(){
var parent = this.parentNode.parentNode.parentNode; // (2)
var n = parent.querySelectorAll(".form-control").length
var f = fieldgroup.cloneNode(true);
f.children[0].id = "question"+n // (3)
f.querySelector(".secondsec").querySelector("button.btn-success").onclick = addinput // (4)
parent.insertBefore(f,parent.querySelector(".clear")); // (5)
}
Create a copy of a field-group to be used as a template
Get the container of input fields
Set the input field id with regard to total number of form-groups in parent
Make sure template applies addinput() to button
Insert input form before end of parent form
The easiest way apply this function to all + buttons is with JQuery
$("button.btn-sm.btn-success").on("click", addinput)
This would need to be located at the bottom of your html file, and below addinput() definition
EDIT: Real Answer
Turns out I wrote all that and just realized I misunderstood your question.
Still we can use the same principle to do what I believe you are asking
master = document.querySelector(".aquestionpart"); // (1)
form = document.querySelector(".questionparts"); // (2)
function show(){
var f = form.cloneNode(true);
var n = master.querySelectorAll(".questionparts").length;
f.id = "questionparts"+(n+1); // (3)
f.querySelector("#questions").onkeypress = show; // (4)
this.parentElement.parentElement.querySelector("#questionparts"+ n + " > .questionshowp").style ="display:block;"; // (5)
this.onkeypress = undefined; // (6)
master.insertBefore(f,master.children[master.children.length-1]) // (7)
}
form.querySelector("#questions").onkeypress = show; // (8)
form = form.cloneNode(true); // (9)
Get poll container
Get poll question form to use as template
Set new poll question form id with respect to number of others
Set show function to new poll question
Show multiple choice
Make sure subsequent keypresses dont create more questions
Insert question before .clear
sets up first question to show
creates copy of fresh question to use as template
With this your current scripts.js is unnecessary, and .aquestionpart must look like this for proper formatting
<div class="aquestionpart">
<div class="questionparts" id="questionparts1">...</div>
<div class="clear"></div>
</div>
From within .questionparts be sure to remove onkeypress="show();" from input. It should look like this.
<input name="questions" id="questions" class="form-control" placeholder="Questions" value="" type="text">
And finally an interesting note is that both of the scripts I've provided can be used together! (With some slight modifications)
//Author: Shane Mendez
var fieldgroup = document.querySelector(".questionshowp .form-group").cloneNode(true);
var addinput = function(){
var parent = this.parentNode.parentNode.parentNode;
var n = parent.querySelectorAll(".form-control").length
var f = fieldgroup.cloneNode(true);
f.children[0].id = "question"+n
f.querySelector(".secondsec").querySelector("button.btn-success").onclick = addinput
console.log(parent)
parent.insertBefore(f,parent.children[parent.children.length-1]);
}
master = document.querySelector(".aquestionpart");
form = document.querySelector(".questionparts");
function show(){
var f = form.cloneNode(true);
var n = master.querySelectorAll(".questionparts").length;
f.id = "questionparts"+(n+1);
f.querySelector("#questions").onkeypress = show;
console.log(this)
this.parentElement.parentElement.querySelector("#questionparts"+ n + " > .questionshowp").style ="display:block;";
this.onkeypress = undefined;
master.insertBefore(f,master.children[master.children.length-1])
$(f.querySelectorAll("button.btn-sm.btn-success")).on("click", addinput)
}
form.querySelector("#questions").onkeypress = show;
form = form.cloneNode(true);
$("button.btn-sm.btn-success").on("click", addinput)
If you put this in your scripts.js file and put that at the bottom of your body tag, then the only thing left is the - buttons.
You can use this Press to add multiple input field inside a div dynamically using jQuery. Here you only need to call the function that takes two parameter HTMLElement and config like:
$(".addInput").click(function() {
build_inputs($(this), config);
});
In the config you can add numbers of inputs form config like:
let config = {
title: "Slides",
forms: [
{
type: "text",
name: "name",
class: "form-control mb-2",
placeholder: "Enter Data..."
},
{
type: "file",
name: "image",
class: "btn btn-light btn-sm mb-2 btn-block"
},
{
type: "number",
name: "mobile",
class: "form-control mb-2",
placeholder: "Enter Data..."
}
],
exportTo:$('#getData')
};

Retrieve the disabled attributes even after page refresh using localStorage

I have an HTML code with a select tag where the options are dynamically populated. Once the onchange event occurs the option selected gets disabled. And also if any page navigation happens the options populated previously are retrieved.
In my case once options are populated and any option is selected gets disabled( intention to not allow the user to select it again). So there might be a case where out of 3 options only two are selected and disabled so once I refresh and the options not selected previously should be enabled. And the options selected previously should be disabled. But my code enables all the options after refresh. How can I fix this?
html code
<select id="convoy_list" id="list" onchange="fnSelected(this)">
<option>Values</option>
</select>
js code
//This function says what happnes on option change
function fnSelected(selctdOption){
var vehId=selctdOption.options[selctdOption.selectedIndex].disabled=true;
localStorage.setItem("vehId",vehId);
//some code and further process
}
//this function says the process on the drop-down list --on how data is populated
function test(){
$.ajax({
//some requests and data sent
//get the response back
success:function(responsedata){
for(i=0;i<responsedata.data;i++):
{
var unitID=//some value from the ajax response
if(somecondition)
{
var select=$(#convoy_list);
$('<option>').text(unitID).appendTo(select);
var conArr=[];
conArr=unitID;
test=JSON.stringify(conArr);
localStorage.setItem("test"+i,test);
}
}
}
});
}
//In the display function--on refresh how the stored are retrievd.
function display(){
for(var i=0;i<localStorage.length;i++){
var listId=$.parseJSON(localStorage.getItem("test"+i)));
var select=$(#list);
$('<option>').text(listId).appendTo(select);
}
}
In the display function the previously populated values for the drop down are retrieved but the options which were selected are not disabled. Instead all the options are enabled.
I tried the following in display function
if(localStorage.getItem("vehId")==true){
var select=$(#list);
$('<option>').text(listId).attr("disabled",true).appendTo(select);
}
But this does not work.
Elements on your page shouldn't have same ids
<select id="convoy_list" onchange="fnSelected(this)">
<option>Values</option>
</select>
In your fnSelected() function you always store item {"vehId" : true} no matter what item is selected. Instead, you should for example first assign some Id to each <option\> and then save the state only for them.
For example:
function test(){
$.ajax({
//some requests and data sent
//get the response back
success:function(responsedata){
for(i=0;i<responsedata.data;i++):
{
var unitID=//some value from the ajax response
if(somecondition)
{
var select=$("#convoy_list"); \\don't forget quotes with selectors.
var itemId = "test" + i;
$('<option>').text(unitID).attr("id", itemId) \\we have set id for option
.appendTo(select);
var conArr=[];
conArr=unitID;
test=JSON.stringify(conArr);
localStorage.setItem(itemId,test);
}
}
}
});
}
Now we can use that id in fnSelected():
function fnSelected(options) {
var selected = $(options).children(":selected");
selected.prop("disabled","disabled");
localStorage.setItem(selected.attr("id") + "disabled", true);
}
And now in display():
function display(){
for(var i=0;i<localStorage.length;i++){
var listId = $.parseJSON(localStorage.getItem("test"+i)));
var select = $("convoy_list");
var option = $('<option>').text(listId).id(listId);
.appendTo(select);
if(localStorage.getItem(listId + "disabled") == "true"){
option.prop("disabled","disabled");
}
option.appendTo(select);
}
}
Also maybe not intended you used following shortcut in your fnSelected:
var a = b = val;
which is the same as b = val; var a = b;
So your fnSelected() function was equivalent to
function fnSelected(selctdOption){
selctdOption.options[selctdOption.selectedIndex].disabled=true;
var vehId = selctdOption.options[selctdOption.selectedIndex].disabled;
localStorage.setItem("vehId",vehId); \\ and "vehId" is just a string, always the same.
}
Beware of some errors, I didn't test all of this, but hope logic is understood.

how to filter the contents of a listbox based on a text box value

i have a html form which contains the following elements
1) a list box (containing a list of filenames)
s1.txt2013
s2.txt2013
s3.txt2012
s4.txt2012
2) a text box (user enters a pattern say 2013)
3) a button
by default list box contains a the above mentioned 4 files names.
when a user enter a a text in the text box (say for example he eneters 2013 in the text box), and press the button, then the list box contents should be filtered out according to the text mentioned in the text box
so in this case after clicking the button, list box should only contain two values (i.e. only those values in which 2013 appears).
s1.txt2013
s2.txt2013
how can i do this.
i did the following way..
i am using a javascript function which will take all the option values of the list box in a javascript array. now i am not able to search the array for 2013 and populate the same list box with the values containing 2013 in in.
can anyone tell me how to do this?
Maybe you need two listboxes (select tags), one of them be hidden as main data source and one of them visible for users, you can use following code and add onclick="buttonClicked()" to you button attributes.
function buttonClicked () {
var textbox = document.getElementById('YOUR TEXTBOX ID'),
listbox = document.getElementById('YOUR SELECT ID'),
mainListbox = document.getElementById('YOUR MAIN SELECT ID');
listbox.innerHTML = '';
for (var childIndex = 0; childIndex < mainListbox.children.length; childIndex++) {
var child = mainListbox.children[childIndex];
if (child.innerHTML.search(textbox.value) != -1) {
option = document.createElement('option');
option.innerHTML = child.innerHTML;
listbox.appendChild(option);
}
}
};
Have you tried using .test? To me this would be a good approach.
http://www.w3schools.com/jsref/jsref_regexp_test.asp
<script>
var str="Hello world!";
//look for "Hello"
var patt=/Hello/g;
var result=patt.test(str);
document.write("Returned value: " + result);
//look for "W3Schools"
patt=/W3Schools/g;
result=patt.test(str);
document.write("<br>Returned value: " + result);
</script>

Populating form text inputs with data-* data using jQuery

I've been trying to wrap my head around this particular issue for two days now. I feel like I'm close, but I can't crack it. I have a div with data-* attributes:
<div class="pull-right" id="actions" data-ph-title="I am a title" data-ph-type="and a type" data-ph-source="from a source" data-ph-subject="with a subject">
When trying to alert - for instance - the value of "data-ph-title", I can do the following as apparently the dash between "ph" and "title" gets removed.
var info = $("#actions").data();
alert(info.phTitle);
That's great and it works (alerts: "I am a title"), but what I really want is to populate certain form fields with all of this data. I have named my form fields identical to the info object's properties, for example:
<textarea id="placeholder-title" name="phName"></textarea>
I'm trying to come up with a loop that will put all of the info object's property values into the corresponding text inputs (or textareas). This is where I'm getting stuck. I currently have the following code:
var info = $("#actions").data();
$.each(info, function(field, val){
$("[name='" + field + "']").val(val);
});
Any help would be greatly appreciated!
Your code works, so I don't really know what the problem is, aside from you not having a field named 'phName'.
This should be what you need. Iterate through the JSON object and populate the text areas:
var info = $("#actions").data();
for (var key in info) {
if (info.hasOwnProperty(key)) {
$("[name='" + key + "']").val(info[key]);
}
}
Here is a jsFiddle that demonstrates it working.
You don't seem to have a phName in #actions. But what about using an id on your form elements?
var info = $("#actions").data();
$.each(info, function(field, val){
$("#placeholder-" + field).val(val);
});
and
<textarea id="placeholder-phTitle"></textarea>
<textarea id="placeholder-phSource"></textarea>
...
Try this:
var fields = $('#myform input, #myform textarea');
for(var i=0; i < fields.length; i++){
var input = fields[i];
if(info[input.name]) input.value = info[input.name];
}

Javascript - filling textboxes with checkbox value

In my web application, I've set of checkboxes which on check populate a textbox above them.(If more than one checkbox is selected, then their values appear in the textbox separated by commas).
These set of checkboxes appear as rows in my HTML table.
Here's my HTML code.
<input type="text" id="newContactComment<%=rCount %>" name="newContactComment" size="45">
<input type="checkbox" id="commentText<%=rCount %>" name="commentText" value="<%=c.getComment_text() %>"
onclick="javascript:updateTextArea(<%=rCount%>);">
And the corresponding JS function is as follows:
function updateTextArea(rCount) {
var allVals = new Array();
$("#contactInfo input['commentText' + rCount]:checked").each(function() {
(allVals).push($(this).val());
});
$("#newContactComment" + rCount).val(allVals);
}
The rCount variable in the above function is the row # of my table.
Using this above, I'm not getting the expected behaviour..
For ex. If for row 1 of my table, I check chkbox 1 and 2, it correctly gets populated with values of those checkboxes. Now, for 2 of my table, I check only chkbox 3, it gets populated with the values 1,2 and 3 and not only 3 as I expect it to.
Any help will be greatly appreciated.
It would be better to use jQuery to set an event handler rather than setting it inline.
You want to use the onchange event not the onclick event.
If you add class names of checkboxes (or whatever you want) to the checkboxes the following will work:
$("input.checkboxes").change(function(){ //when checkbox is ticked or unticked
var par = $(this).closest("tr")[0];
var parID = par.id;
var patt1=/([0-9]+)$/g;
var rCount = parID.match(patt1); //Gets number off end of id
var allVals = new Array();
//Get all checkboxes in current row that are checked
$(par).find("td input.checkboxes:checked").each(function() {
allVals.push($(this).val());
});
$("#newContactComment" + rCount).val(allVals);
allVals = null; //empty array as not needed
});
I believe this or something along these lines will do what you want
You're trying to use the rCount variable from within the quoted string. Try this instead:
$("#contactInfo input['commentText" + rCount + "']:checked")

Categories

Resources