How get get dynamically generated value - javascript

The following contain dynamic values
<c:forEach items="${allUserList}" var="eachUser">
<span class="name"> ${eachUser.getUserName()} <span>
<select class="role">
<c:forEach items="${roleList}" var="eachRole">
<option value="${eachRole.getRoleName()}">${eachRole.getRoleName()}</option>
</c:forEach>
</select>
<input type="button" class="add" value="add" />
</c:forEach>
When i click on add button i should see corresponding name, selected role in a alert box (e.g {jack, admin})
How to do this??

Using the class attribute of the button as a selector, you can use the .prev function to find the <select> element preceding the button:
$(".add").on("click", function() {
alert($(this).prev(".role").val()); // Role
alert($(this).prevAll(".name").text()); // Name
});
You don't need event delegation in this instance, as JSP will generate this code before it reaches the client.

Related

How can I dynamically select input field in dynamically generated forms with Javascript/jQuery?

When my document is ready I have 1 or more identically forms with select and two inputs that I want to show (1 of them based on select dynamically).
For 1 form its pretty simple, but my problem is that forms are generated dynamically like when I have on ready 1 form select tag is looking like this
<button type="button" class="add-document-item btn btn-success btn-sm pull-right">
<i class="glyphicon glyphicon-plus"></i>
</button>
<select id="type" class="form-control">
<option value="1">File 1</option>
<option value="2">File 2</option>
</select>
<div class="col-md-12 system" id="system">
My YII2 active form field...
</div>
<div class="col-md-12 computer" id="computer">
My YII2 active form field...
</div>
If after opening document and there is more than 1 form OR there is one and I adding more by myself dynamically, SELECT id's generating like "type0", "type1", "type2" and same is with form fields id's.
So far I can only switch inputs dynamically only when 1 form is rendered
$(document).ready(function () {
$('#computer').hide();
$(document).on('change', '#type', function () {
var val = $('#type').val();
if (val == 2) {
$('#system').show();
$('#computer').hide();
} else {
$('#computer').show();
$('#system').hide();
}
});
});
My need is to change selected input for every generated form individual. I am stuck for this already for some time. Can anybody can help me?
This javascript I created should do the trick. You'll need to apply this to your own code.
Declare an array with all form elements
Select all elements you are going to loop through
Use forEach and overload it with the array you created
Create an if statement with the right filter set
myArray = document.querySelectorAll('form')
document.querySelectorAll('form').forEach(function(value, index,
myArray){
if (myArray[index].getAttribute('id')=='system'){
console.log('system') //doSomething()
}
})
You can refactor this by replacing the 2th instance of document.querySelectorAll('form') with myArray, but for clarity I'll leave it as is.

How to use checked input values used for math as part of cloned div elements

I have written a script that clones a certain div as required by the user. Within the div there are three checkbox input options and each option as a numeric value. I want the script to allow the user to select a checkbox and then the value will be reflected in another input space and each value that are added will be separated by a comma.
The tricky part is that it should be done for each clone, and that each checkbox has the same class name to which the script should be written. I realize that using unique id's would be better, but I would like it that a for loop could do it for any number of checkboxes under the specific class.
Here is the html script:
<style>
.hidden {
display: none;
}
</style>
<body>
<h2>Test</h2>
<button id="add">Add</button>
<div class="test hidden">
<div class="user_input1">
<label>Input1</label>
<input class="input1" type="text" required>
<label>Input2</label>
<input type="text" name="value2" required>
<div class="user_input2">
<table>
<thead>
<tr>
<th>Pick Option</th>
</tr>
</thead>
<tbody>
<tr id="append">
<td><input class="test" type="checkbox" name="test" value="1">Test1</td>
<td><input class="test" type="checkbox" name="test" value="2">Test2</td>
<td><input class="test" type="checkbox" name="test" value="3">Test3</td>
</tr>
</tbody>
</table>
<input type="text" id="insert" name="check">
<button class="hidden" id="testbtn">Calc</button>
</div>
</div>
</div>
<form action="server/server.php" method="POST">
<div class="paste">
</div>
<button type="submit" name="insert_res">Submit</button>
</form>
</body>
And my attempt for the jQuery:
$(document).ready(function() {
var variable = 0
$("#add").click(function() {
var element = $(".test.hidden").clone(true);
element.removeClass("hidden").appendTo(".paste:last");
});
});
$(document).ready(function(event) {
$(".test").keyup(function(){
if ($(".test").is(":checked")) {
var test = $(".test").val();
};
$("#insert").val(test);
});
$("#testbtn").click(function() {
$(".test").keyup();
});
});
I think a for loop should be used for each checkbox element and this to specify each individual clone, but I have no idea where or how to do this. Please help!
I am assuming you already know how to get a reference to the dom element you need in order to append, as well as how to create elements and append them.
You are right in that you can loop over your dataset and produce dom elements with unique id's so you can later refer to them when transferring new values into your input.
...forEach((obj, index) => {
(produce tr dom element here)
(produce three inputs, give all unique-identifier)
oneOfThreeInputs.setAttribute('unique-identifier', index); // can set to whatever you want, really
(proceed to creating your inputs and appending them to the tr dom element)
targetInputDomElementChild.setAttribute('id', `unique-input-${index}`); // same here, doesn't have to be class
});
Observe that I am using template strings to concat the index number value to the rest of the strings. From then on, you can either reference the index to refer to the correct input or tr using jquery in your keyUp event handler:
function keyUpEventHandler($event) {
const index = $(this).attr('unique-identifier');
const targetInput = $(`#unique-input-${index}`)
// do stuff with targetInput
}
I have created a fiddle to show you the route you can take using the above information:
http://jsfiddle.net/zApv4/48/
Notice that when you click an checkbox, in the console you will see the variable number that designates that set of checkboxes. You can use that specific number to get the input you need to add to and concat the values.
Of course, you still need to validate whether it is being checked or unchecked to you can remove from the input.

check if target element is first element in class

I need to check if the element targeted is first element in its class and perform actions accordingly.
For eg. I have a select element with class name 'team'.
Now I need to check if the selected element is whether a first element or not.
Here's my HTML:
Initially there's a single select and checkbox input. On clicking a button, more select and checkbox inputs are added.
<div class="col-sm-7" id="include-fields">
<select name="team[]" class="form-control team" id="team">
<option></option>
<option value="1">1</option>
</select>
<label>Lead</label>
<input type="checkbox" name="lead_check[]">
</div>
<div class="col-sm-offset-2">
<button id="includes" class="btn btn-success"><i class="fa fa-plus"></i>
</button>
</div>
Dynamic select and checkbox generating:
$('#includes').click(function(e)
{
e.preventDefault();
$('#include-fields').append('<div class="holder-includes"><i class="fa fa-trash-o pull-right"></i>' +
'<select name="team[]" class="form-control team">'+
'<input type="checkbox" name="lead_check[]"></div>');
var items = "";
$.post("teamFetch", function(data)
{
$.each(data,function(index,item)
{
items+="<option value='"+item.id+"'>"+item.title+"</option>";
});
$(".team:last").html(items);
}, "json");
});
I tried following, but no luck:
$(document).on("change",".team",function(e){
var target = $(e.target);
if(target.is(".team:first"))
{
$(this).parent('div#include-fields').find("input[name='lead_check[]']").val($(this).val());
}
$(this).siblings("input[name='lead_check[]']").val($(this).val());
});
Here, first select element is already there, but other select elements are added dynamically later. They all have the same class team.
To check if the select element is a first child of its parent among all the sibling you can use this script.
$(document).ready(function(){
$(document).on("change","#include-fields .team:first",function(){
alert($(this).val());
});
});
Alert will only get triggered on the first select element. Here is a fiddle

How to get current element in order to select with javascript?

I've got the follwoing HTML structure (I do not have the IDs of the following elements because they are dynamically created):
<fieldset>
<div class="classA">
<select onchange="updateInputBox()">
<option>a</option>
<option>b</option>
<option>c</option>
<option>d</option>
</selects>
</div>
<div class="classB">
<input data-myAttribute="case1">
</div>
<div class="classC">
<a type="button">
<i class="fa fa-remove">x</i>
</a>
</div>
</fieldset>
The filedset and it's children is dynamically created. I want to change the attribute in the inputBox depending on what the user selected in the selectBox.
Here is an example how I would have done if the element fieldset would not have been dynamic (the following contains elements have IDs, but only because I want to demonstrate what I want; in reality I don't have IDs because they are dynamically created by clicking a button, that I do not show here):
https://jsfiddle.net/thadeuszlay/6bsgazvv/4/
But unfortunately I don't have the id of the fieldset, because it is dynamically created. Is there a way how you can get the position of the current element?
I tried to pass itself in the updateInputBox-function:
<select id="selectBox" onchange="updateInputBox('+ this +')">
I also tried with jQuery:
$(this).parent().parent()
but in both cases the console would say
"Unexpected identifier"
Update:
Inside the function doing something like this (currentElement is the selectBox/DropDownBox):
currentElement.parent().parent().setAttribute("data-myAttribute", "hello");
Uncaught TypeError: selectBox.parent is not a function
You can use jquery 'closest' for this as below.
HTML
<select id="selectBox" onchange="updateInputBox(this)">
JS
function updateInputBox(selectElm) {
var inputElm = $(selectElm).closest('fieldset').find('input');
inputElm.attr('data-myAttribute', $(selectElm).val());
}
// instead of inline onchange event and the above code, you can use the below to trigger the event
$(document).on('change', 'fieldset select', function () {
var inputElm = $(this).closest('fieldset').find('input');
inputElm.attr('data-myAttribute', $(this).val());
});
In updateInputBox, simply look at the selectedIndex of #selectBox
<select id="selectBox" onchange="updateInputBox(this)">
function
function updateInputBox(dropdowntBox) {
var inputBoxField = document.getElementById("inputBox").setAttribute("data-myAttribute", dropdowntBox.value);
}
Here is jquery version:solution
You need to trigger change() event for select with ID selectBox
$(document).on('change','select',function(){
var value=$(this).val();
$(this).parents('fieldset').find('input').attr('data-myAttribute',value);
});

How to delete a row based on its index?

I want to delete a selected row using jQuery. First, while clicking add button, rows are added dynamically with a delete button. Now I want to delete the selected row.
I am using the following code to add rows dynamically:
$("#btnAdd").on('click', function (){
$('#Time tr').last().after('<tr><td><span style="font-size:14px;">Diplamo/Certificate :</span><input type="textbox" input id="addedValue12" name = "Certificate"></td><td><span style="font-size:14px;">Percentage :</span><input type="textbox" id="addedValue123" name = "CertificatePer"></td></tr>');
});
<input id="btnAdd" type="button" value="add" />
<table id="Time">
<tr>
</tr>
</table>
I am displaying values in a JSP page.
<c:forEach var="var1" items="${empedu.empCertificate}">
Certificate Name:<input value="${var1.certification}" name="Certificate" type="text" title="Only Text Allowed" pattern="[a-zA-Z\s'.,#:&?!()$#/\\]+" />
Percentage: <input value="${var1.percentage}" name="CertificatePer" style="width: 100px;" type="text" max="100" />
<input type="button" id="deleteRow" name="delete" value="delete" /><br/>
</c:forEach>
It is displayed on screen like this:
Here, If I click the third row, I want to delete the third row. How can I do this?
$("#Time").on("click", ".delete", function(){
$(this).closest("tr").remove();
});
Assuming delete is the class of the delete button. I have used .on as the rows and thus delete buttons are dynamically added.
This is picking the closest tr from the clicked delete button, and removing it.
Working Fiddle
1st: Id must be unique so don't use id for more than one element .. use class instead
2nd: while you append rows you need to jQuery event delegation ...
$('#Time').on('click' , '.delete' , function(){
// change .delete_btn with your delete btn class
$(this).closest('tr').remove();
});

Categories