Dynamic id for HTML element which is getting created newly - javascript

I am replacing a span inside a table > td with option box.
I want to assign some unique id with dynamic value while creating the option box. How to achieve this?
Unique id is already generated , I want to set this unique id in Html while creation.
<td id="tdTest">
<span id="spanId" class="connectedSlot" style="color:rgb(27,99,173)">Enabled</span>
</td>
$("#"+spanId).replaceWith(function () {
return "<select class='form-control' id=<<DYNAMIC ID>> style='width:200px;'><option value='0'>Enabled</option><option value='1'>Disabled</option></select>";
});
For example , I will get some value from and assign to a variable and later assign this variable to id.
var myId = "OptionId"+test;
select class='form-control' id=myId style='width:200px;'>
Thanks

Use a variable within a string like this:
var unqiueID = "myID123", ret = "";
ret = "<select class='form-control' id='" + unqiueID +"' style='width:200px;'>";

One possible way to ensure that a unique value is assigned is to keep track of all the available id's and assign an id which isn't there in our list.
getUniqueId() is a function that will always return a unique id.
function getUniqueId() {
//get all the ids in this document
var ids = new Array();
$('[id]').each(function() { //Get elements that have an id=
ids.push($(this).attr("id")); //add id to array
});
//give some random value to uniqueId
//if this value is in ids array, then assign a different id and recheck the condition
var uniqueId;
while(true) {
uniqueId = 'some-prefix-' + Math.floor(Math.random() * 10000);
if($.inArray(uniqueId , ids) == -1) {
break;
}
}
return uniqueId;
}

Possible Solution:
function randomString(length) {
return Math.round((Math.pow(36, length + 1) - Math.random() * Math.pow(36, length))).toString(36).slice(1);
}
Look into these Questions for others: link link

It's been several years since this was posted, and the accepted solution didn't work for me. Here is the syntax that did:
[id]="unqiueID"

Related

How to select by id in array of elements in JavaScript

I'm struggling a bit with how to do a simple selection of a specific element in a element array in JavaScript. Consider the following:
var htmlString = "<span>someText</span><input type='hidden' class='idBox' name='id' data-id='6026' value='6026'>";
var eleArray = $.parseHTML(htmlString);
var inputVal = $(eleArray[1]).val();
inputVal will hold the value of the input field. In this specific case it would be hold 6026.. However I don't like the way I get this value by selecting index 1 in the eleArray, which is the input element. I would like to select it by the input elements id, which in this case by class would be idBox or name id.. But I don't know how to do that.
Any advice ?
parseHTML will give you an array of elements which you can use with jQuery, so you can filter in the usual way you would with elements added to the DOM:
var htmlString = "<span>someText</span><input type='hidden' class='idBox' name='id' data-id='6026' value='6026'>";
var eleArray = $.parseHTML(htmlString);
var inputVal = $(eleArray).filter("[name='id']").val()
console.log(inputVal);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
You can use the class selector syntax :
const htmlString = "<span>someText</span><input type='hidden' class='idBox' name='id' data-id='6026' value='6026'>";
$($.parseHTML(htmlString)).filter(".idBox").val();
// => '6026'
Other solution using the input name :
const htmlString = "<span>someText</span><input type='hidden' class='idBox' name='id' data-id='6026' value='6026'>";
$($.parseHTML(htmlString)).filter("input[name='id']").val();

getElementById() in for loop to retrieve input values

In a for loop, I am using getElementById() to retrieve several input values in javascript.
First I made a bunch of input boxes and set the different id's using a for loop.
Now I'm using a second for loop to reference those id's and retrieve their input values.
Code:
for (i=0;i<products.length;i++){
var display;
display ="<input type='number' id="+products[i][0]+" onchange=myFunction()>";
document.write(display);
}
document.write("<p id=demo></p>");
function myFunction() {
var totalVeg=0;
for (j=0;j<products.length;j++){
amount = document.getElementById(products[j][0]).value;
totalVeg += amount;
}
document.getElementById("demo").innerHTML = "You selected: " + totalVeg;
}
</script>
Specifically I'm having trouble with this part:
amount = document.getElementById(products[j][0]).value;
If I reference a specific input, like products[0][0], the value will be found. It is only when I try to reference an id using the "j" variable then the code stops working.
I've read through some of the other questions and answers on here but none are exactly what I want.
Thanks!
<script type="text/javascript">
var products = ["Saab","Volvo","BMW"];
for (i=0;i<3;i++)
{
var display;
display ="<input type='number' id='"+products[i]+"'onchange=myFunction(this.id)>";
document.write(display);
}
document.write("<p id=demo></p>");
var totalVeg=0;
function myFunction(_this) {
amount = parseInt(document.getElementById(_this).value);
totalVeg += amount;
document.getElementById("demo").innerHTML = "You selected: " + totalVeg;
}
</script>
You can take it as a reference. Hope it helps.
seem you don't have the quote around the id andbthen the id is not properly defined try this way
for (i=0;i<products.length;i++){
var display;
display ="<input type='number' id='"+products[i][0]+"' onchange=myFunction()>";
document.write(display);
}

Adding custom attribute values of dynamically created dropdowns to another element

I have a bit of HTML here:
<tr taskId="(#=obj.task.id#)" assigId="(#=obj.assig.id#)" class="assigEditRow" >
<td><select name="resourceId" class="get-resources formElements"></select></td>
<td><span class="resources-units"></span></td>
<td><span class="resources-quantity"></span></td>
<td><input type="text" placeholder="Required Q"></td>
<td align="center"><span class="teamworkIcon delAssig" style="cursor: pointer">d</span></td>
</tr>
And a bit of JS here:
'use strict';
function addResourceFunction(){
let ResourcesJSON = (json) => {
let Resources = json;
console.log(Resources);
let contactsLength = json.length;
let arrayCounter = -1;
let resID;
let resName;
let resUnit;
let resQuantity;
let Option = $('<option />');
let assignedID = $('tr.assigEditRow:last').attr("assigId");
while(arrayCounter <= contactsLength) {
arrayCounter++;
resID = Resources[arrayCounter].ID;
resName = Resources[arrayCounter].name;
resUnit = Resources[arrayCounter].unit;
resQuantity = Resources[arrayCounter].quantity;
$('.assigEditRow').last().find('select').append($('<option>', {
value: resName.toString(),
text: resName.toString(),
resourceID: resID.toString(),
resourceUnit: resUnit.toString(),
resourceQuantity: resQuantity.toString()
}));
}
}
$.getJSON("MY JSON URL IS HERE", function(json) {
ResourcesJSON(json);
});
};
So what's actually going on here: I get my data from the URL (JSON array), trigger the addResourceFunction() on click to create a new table row and to add a new select with options passed from the array. As you see from my HTML markup, the select input is placed in td.get-resources, and all that works good. I get my date set, I populate the select field and all works good. I can add as many rows/select dropdowns as I want.
Also, every option has a few custom attributes (you can see it in my JS code above), and I want to add the values of those attributes to the second and third column of the row (in HTML those are span.resources-units and span.resources-quantity). The thing is, I have no clue how to make it work 1:1, meaning that one select dropdown "alters" only units and quantity of its own row. Below is the code for that:
let idCounter = 1;
$(document).on('change', '.get-resources', function() {
$('.assigEditRow').last().find('.resources-units').attr('id', 'units-' + idCounter);
$('.assigEditRow').last().find('.resources-quantity').attr('id', 'quantity-' + idCounter);
this.resourceUn = $( ".get-resources option:selected" ).attr( "resourceUnit" );
this.resourceQuant = $( ".get-resources option:selected" ).attr( "resourceQuantity" );
$('#units-' + idCounter).append(this.resourceUn);
$('#quantity-' + idCounter).append(this.resourceQuant);
idCounter++;
});
What happens is that if I add one select input, and change options, the thing works. When I add another one and change its options, it gets attributes of the first one. Adding more - same thing. Whatever I change, it takes the attribute value of the first item added.
Try getting the id from the element instead of from the variable, since you always update the element with the id of the counter, instead of the element with the id of the row that was clicked.
Hmm, what does the counter do exactly? The more I look at it, the less I understand. What I do know is that you're not selecting the correct elements by using the idCounter to reference the correct row.
You want to do something like
$(document).on('change', '.get-resources', function() {
//var row = this;
this.find(/* Some path to the second column */).att(/* some att to change */);
this.find(/* Some path to the third column */).att(/* some att to change */);
});
where you always use the row as the root again, instead of finding a certain id, so you only update that row.
Native:
<table>
<tr>
<td>
<select>
<option data-text="resName1" data-resourceID="resID1" data-resourceUnit="resUnit1" data-resourceQuantity="resQuantity1">1</option>
<option data-text="resName2" data-resourceID="resID2" data-resourceUnit="resUnit2" data-resourceQuantity="resQuantity2">2</option>
<option data-text="resName3" data-resourceID="resID3" data-resourceUnit="resUnit3" data-resourceQuantity="resQuantity3">3</option>
</select>
</td>
<td>
<div class="column2"></div>
</td>
<td>
<div class="column3"></div>
</td>
</tr>
</table>
<script>
document.addEventListener('change', function ( event ) {
var select = event.target,
option = select.options[select.selectedIndex],
values = {
'text' : option.getAttribute('data-text'),
'resourceID' : option.getAttribute('data-resourceID'),
'resourceUnit' : option.getAttribute('data-resourceUnit'),
'resourceQuantity' : option.getAttribute('data-resourceQuantity')
},
row = select.parentNode.parentNode,/* depending on how deep the select is nested into the tr element */
column2 = row.querySelector('.column2'),
column3 = row.querySelector('.column3');
column2.textContent = 'some string with the values you want';
column3.textContent = 'some string with the other values you want';
});
</script>
Basically you start with the select that was changed, from there you get the option node that was clicked. Then you get the attributes you need from that option. Then you go up a few nodes to the row parent and find the two columns inside that row. Then you can set the content of these two columns.

Adding more than one value to text box

I'm trying to allow users to add a list of 'favourites' to a text box but when adding more than one value it replaces the value already there. Can anybody help? Thanks this is my code:
var name
function getFavourite() {
name = "Student 1, ";
$('#output').val(name)
saveFavourites();
}
function getFavourite2() {
name = "Student 2, ";
$('#output').val(name)
saveFavourites();
}
function saveFavourites() {
var fav = $("#output").val();
if (fav !== "") {
localStorage[name] = $("#output").val();
$("#output").val(name);
}
}
function loadFavourites() {
var fav = $("#name").val();
if (name !== "") {
$("#output").val(localStorage[name]);
$("#name").val("");
}
}
using val will replace the existing value as you already noticed so i would do something like this if you want to add to that value.
$("#output").val($("#output").val() + ', ' + name);
At least if i understand you correctly. This would get the excising value and then add the new value to it (in this case with a comma but is not necessary)
Of course if you need the same element twice or more is better to assign it to a var instead of calling the selector twice.
I think you are looking into multiple select dropdown, something like this:
http://codepen.io/martynasb/pen/kawxq
You don't an text input, you want a select where you can select multiple values. In html, it's <select multiple>.
The plugin I know that provides the best experience for this is is Select2: http://ivaynberg.github.io/select2/#basics
And you don't have to load all the options right away, they can be fetched via ajax easily.

How to get id from generated list in jquery

$ctr = 0;
foreach($authspons as $authspons_list){
$ctr++;
echo "<input type='checkbox' id='id_list'".$ctr."'"." name='authspons[]'"." class='list_check' value='".$authspons_list->authspons_position." ".$authspons_list->authspons_lname.",".$authspons_list->authspons_fname." ".$authspons_list->authspons_mname." ".$authspons_list->authspons_cmpny.'; '."'".">" .$authspons_list->authspons_position." ".$authspons_list->authspons_lname.",".$authspons_list->authspons_fname." ".$authspons_list->authspons_mname." ".$authspons_list->authspons_cmpny."</input> <br />";
echo "<input type='text' class='text_list' id='tbox".$ctr."'"."name='authsponsid[]' value='".$authspons_list->authspons_id."; "."'"." >";
}
I have a generated list coming from database, the checkboxes contains the personal details, while the textboxes contains the "ID" of each items in the checkboxes.
This is my jquery code:
$('#list').click(function(){
var final = '';
var final2='';
$('.list_check:checked').each(function(){
var values = $(this).val();
final += values;
var val_id = $('.text_list').val();
final2 +=val_id;
});
$("#coauth").val(final);
$("#coauthid").val(final2);
$("#coauthspons").modal("hide");
});
Getting value from checkboxes is okay. My problem is: the output from the textbox is always the last value of the number of checkboxes that is checked.
Like this:
1st checkbox = 1st textbox(value="1");
2nd checkbox = 2nd textbox(value="2");
when i check the two options, the textbox only results to:
1st checkbox = 1st textbox(value="2");
2nd checkbox = 2nd textbox(value="2");
How do I get the result of each of the expected checkbox and its textbox value?
here var val_id = $('.text_list').val();
you are giving the same value for all the elements irrespective of their index
try like this
var val_id = $(this).next().val(); //this gives value of next i.e .text_list element
$('#list').click(function(){
var final = '';
var final2='';
$('.list_check:checked').each(function(){
var raw_value = $(this).val();
var id_value = raw_value.split("||");
var values = id_value[1];
final += values;
var val_id = id_value[0];
final2 +=val_id;
});
$("#coauth").val(final);
$("#coauthid").val(final2);
//alert(final2);
$("#coauthspons").modal("hide");
});
Thanks #Bhadra for your answer. it gives me an idea but I found a better solution to my own problem. I put all the values in the checkbox then I use split function to separate the "ID" from the original checkbox values(fname,mname,lname).

Categories