javascript/jquery mutate and append html in var - javascript

I got a simple array like this:
var arr = ['string_1', 'string_2'];
And I got the following html (simplified, but original is very large):
var html = '<div><input class="myInput" type="text"></div>'
I need to append to #main_div in my DOM this html variable, but filled with values from arr, so in this case there should be 2 inputs, filled with string_1 and string_2.
I tried the following code:
$.each(arr, function(k, v){
$(html).find('.myInput').val(v);
$('#main_div').append(html);//mutated html var should be here
});
but I get 2 empty inputs. Any ideas how to fix it would be welcome. Thank you

Your logic is almost there, but the problem is that you're not storing the jQuery object that you create from the html string, so you just append the unchanged original value. Try this:
var arr = ['string_1', 'string_2'];
var html = '<div><input class="myInput" type="text"></div>'
$.each(arr, function(i, v) {
var $html = $(html).find('.myInput').val(v).end();
$('#main_div').append($html);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="main_div"></div>
Note the use of end() which returns the originally selected element (the outer div from the html string in this case) instead of the .myInput element resulting from the find() call.
Finally, you need to give the input elements name attributes to ensure they are still valid HTML.

Related

javascript html label displaying incorrect values

I have a string that coming from a database something like this test (test<sup>®</sup>) that I would like to display in a label. I try to parse the text but it displays just the last value in the string. I did try to set the innerHTML value to the string and that didn't display any value.
Is there any other way to fix this?
strHTML = $.parseHTML('test (test<sup>®</sup>)');
var Name = "";
$.each(strHTML, function (i, el) {
Name = el.wholeText;
});
$(".lbl-drug").text(Name);
strHTML = $.parseHTML('test (test<sup>®</sup>)');
$(".lbl-drug").html(strHTML);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label class="lbl-drug"></label>

Use of parent and find to select an item in the DOM

I have this js to update a span value with a new value coming from some math.
$('.ammesso').blur(function(){
ammesso = $(this).val();
perc_worst ='<?php echo $az_info['perc_worst']; ?>';
if(isNaN(ammesso)){
console.log(ammesso);
}else{
flusso = ammesso*perc_worst/100;
var jsonObject = $.parseJSON(prevs);
console.log(prevs);
$.each(jsonObject, function (i, obj) {
console.log(obj.id);
var id_item = obj.id;
//it gets the right value of 393
console.log('testo: '+$(this).parent('fieldset').find('.cl'+id_item).text());
});
console.log('flusso calcolato: '+flusso);
}
});
The html is the following:
<fieldset>
<label>Ammesso: </label><input type="text" name="ammesso[0]" value="" class="ammesso numerico">
<label>Incassi previsti: </label>
<ul id="lista">
<li class="soff_grp">Value - <span class="cl393">CASH</span></li>
</ul>
</fieldset>
console.log('testo: '+$(this).parent('fieldset').find('.cl'+id_item).text()); should return what is now inside the span but I miss what is wrong and why I cannot select the span.
My assumptions are:
with .parent('fieldset') I come back to the first DOM element input
and span have in common
with .find('.cl'+id_item) I get the first element with that class
(that is present in the rendered HTML)
What is wrong in how I use this two selectors? As per what I understand of what I have read in the jQuery documentation it seems to me the right way to select it!
the context of input element is lost in each function. this refers to element in jsonObject on which you are iterating. You need to store the element context outside each loop and then use it in each function:
var fieldset = $(this).parent('fieldset');
$.each(jsonObject, function (i, obj) {
console.log(obj.id);
var id_item = obj.id;
//it gets the right value of 393
console.log('testo: ' + fieldset.find('.cl'+id_item).text());
});

Get all form values into javascript array

I am attempting to get all the form values into a normal array[]. I had it working for tags but then I added some tags and can't seem to get it.
With just tags it worked with this
var content = document.querySelectorAll("#form input[name='content[]']");
I am currently trying something like this
var content = document.elements["content[]"].value;
This form can change from user input down the road as each section of the form is a module that they choose to add. It is also important to get the values in order, if that isn't possible then I would need to make it a JSON array. Pure javascript or jquery is fine either way.
Thank you for any help.
EDIT
I used this to solve my problem
var contents=[]
var content = $('#form').serializeArray()
for (var i = 0; i < content.length; i++) {
contents[contents.length]=content[i].value
};
Try
html
<form id="form">
<input type="text" name="content[]" value="abc" />
<textarea name="textarea" value="">123</textarea>
</form>
js
$(function() {
var form = $("#form");
// escape `[]`
var content = form.find("input[name=content\\[\\]]");
// array `literal declaration`
var _arr = [content.prop("value")];
// map all form values to single array
var arr = $.map(form.serializeArray(), function(v, k) {
return [v.value]
});
// array literal with `textarea` `value`
var t = [$("textarea").prop("value")];
console.log(_arr, arr, t);
// _arr: `["abc"]` , arr:`["abc", "123"]` t:`["123"]`
})
Demo.
See Arrays

Javascript handle 2 data attribute

I need to use data attribute in my html
like
<div id="userlist" data-user="A.A.M"></div>
then I need to alert the data-user
I used
var userlist = document.getElementById("userlist");
var show = userlist.getAttribute("data-user");
alert(show);
My question is how to handle many data-user in the html like
<div id="userlist" data-user="A.A.M"></div>
<div id="userlist2" data-user="A.A.M2"></div>
to alert A.A.M and A.A.M2
Thanks in advance and sorry for my bad English.
You could select your elements by attribute.
$("div[data-user]").each(function() {
var user = $(this).data("user");
alert(user);
});
If you have multiple attributes per element (<div data-user='something' data-another='another'></div>), you can also access those in the same way:
$("div[data-user]").each(function() {
var user = $(this).data("user");
var another = $(this).data("another");
alert(user + ", another: " + another);
});
you know how to alert 1, alert 2:
alert at the same time:
var data1 = document.getElementById("userlist").getAttribute("data-user");
var data2 = document.getElementById("userlist2").getAttribute("data-user");
var data = data1 +"\n" + data2; //"\n" can be other separators you like
alert(data)
if you have many of them, you can use jQuery:
add this in your , before any other js code.
<script src="http://code.jquery.com/jquery-2.1.1.min.js"></script>
then :
$("div[id^=userlist]").each(function(){
alert($(this).attr("data-user"));
});
Calling getElementById on both should work. If you want to iterate you can try to use getElementsByTagName or getElementsByClassName. If you want to select any arbitrary element with the attribute data-user, you can either use querySelectorAll, or check out jQuery, and use $("[data-user]") as a selector.
Does that answer your question?

How to iterate through HTML nodes to find matches and get the next innerHTML from a node

I have a form element <select> to select a person. As soon as the element has changed
the function getPerson() is executed and reads out the value of the selected entry.
<select id="cust_id" name="f_cust_id" onchange="getPerson(this)">
<option value="51">Brad Pitt</option>
<option value="123">Angelina Jolie</option>
<option value="13">Jennifer Aniston</option>
</select>
The next step is: that I have a hidden text in the same page, where I want to find this value (example value 51).
I need to iterate trough this hiddenCustomer nodes.
Hidden HTML Text
<div id="hiddenCustomer" style="display:none;">
<span>51</span><span>Brad;Pitt;Y1;Group1;bpitt#wwz.com;12345</span>
<span>123</span><span>Angelina;Jolie;Y2;Group2;ajolie#wwz.com;12346</span>
<span>13</span><span>Jennifer;Aniston;Y1;Group1;ja#wwz.com;12347</span>
</div>
finally if I have a match 51=51 I take the string from the next element and "split" it to an array. It will be used to fill out some formular fields like: firstname, lastnamem, floor, group, email...
My question is: how to iterate best trough the hiddenCustomer nodes. Find the match and take the innerHTML value from
the next element ( example : Brad;Pitt;Y1;Group1;bpitt#wwz.com;12345)
ps: I don't want to use JSON Objects.
You can do like this
[DEMO] --> http://fiddle.jshell.net/ykF6P/
function getPerson(element)
{
var val = element.value;
var $span = $('#hiddenCustomer span').filter(function(){
return $(this).text() == val;
}).next('span');
}
function getPerson(element){
var elementsArray = [];
$("#hiddenElement").each(function(){
$(this).find("span").each(function(){
if($(this).text() == $(element).val()){
elementsArray = $(this).find("span").next().text().split(';');
}
});
});
}
You end up with an array of strings.
You can do this:
var value = 51;
var $span = $('#hiddenCustomer span:nth-child(odd)').filter(function(){
return parseInt($(this).text(),10) == value;
}).next('span');
console.log($span.html());

Categories

Resources