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();
Related
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"
I am looking for a way to add the following row of inputs using a button (and I've found plenty of examples) BUT most of them renames the name of html element (e.g. name = 'price1', name = 'price2') but my javascript references the element's id, making it erroneous when new rows are added. Some helps are appreciated.
JS Fiddle just to see the rows
https://jsfiddle.net/n4h5uwvk/
the HTML code
<form action = "" method = "POST">
<label>Item : </label>
<select id = 'item_name' name = 'item_name' onChange = 'listMatch(this);fieldCheck();'
>
<option value = "" disabled = "disabled" selected="selected">Please Select</option>
<?php
while($row = mysqli_fetch_assoc($result)){
echo "<option value = '".$row['PRODUCT_ID']."' data-price ='
".$row['UNIT_PRICE']."' >".$row['PRODUCT_NAME']."</option>";
}
?>
</select>
<label>Price : </label>
<input type = 'text' id = 'item_price' name = 'item_price' value = '' disabled/>
<label>Quantity : </label>
<input type = "number" id = 'quantity' name = 'quantity' max = "150" min = "0" onChange = 'multiplier(value)' disabled/>
<label>Sub-Total : </label>
<input type = "number" id = 'sub-total' name = 'sub-total' disabled value = ''/>
and the Javascript
<script>
//lists the price according to selected item
function listMatch(product){
var x = product.options[product.selectedIndex].getAttribute('data-price');
document.getElementById('item_price').value = x;
}
//un-disable quantity field after item is selected
function fieldCheck(){
document.getElementById('quantity').removeAttribute('disabled');
}
//var z = quantity*price
function multiplier(value){
var x = document.getElementById('item_price').value;
var y = value;
var z = x*y;
document.getElementById('sub-total').value = z.toFixed(2);
}
//clone fields on 'add field' button click
Updated :
I found a code to clone my forms well, but I encounter another problem. The clone will always duplicate values of the first row, I want to create child rows that have empty values. Any ways around this code?
//global variable for duplication identification
var count = 1;
//clone form for multiple entries
(function() {
$('#add').click(function() {
var source = $('form:first'),
clone = source.clone();
clone.find(':input').attr('id', function(i, val) {
return val + count;
});
clone.insertBefore(this);
count++;
});
})();
As you know id has to be unique and adding numbers to the cloned form elements to keep the ids unique seems overdoing it.
Names don't have to be unique though, so you can have different forms with elements with the same name. And they can be accessed easily by their names:
<form name="form_1">
<input name="firstName" type="text" />
<input name="lasttName" type="text" />
</form>
<form name="form_2">
<input name="firstName" type="text" />
<input name="lasttName" type="text" />
</form>
You can use the form name to access specific element, to access the input with name="firstName" in form_1 and form_2 you can use:
var firstName1 = document.form_1.firstName;
var firstName2 = document.form_2.firstName;
So it will be easy to distinguish between different forms, although their elements have the same structure and names. You just create a new form with name="form_X" and use innerHTML to add the cloned elements.
And to clone an element you can use .cloneNode(true); (or jQuery's clone()).
EDIT:
You still seem to think of it that you need to store everything in a variable, here's an example to do it all, and you can see it's much simpler than you think. I give these forms class="contactForm" to separate them from other forms there might be. we can clone 10 .contactForm and have 100 other forms in the page as well.
To get number of forms you can use $('form.contactForm').length
To empty text inputs inside new form you can use: newForm.find('input[type=text]').val("");
jsfiddle DEMO
$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).
I'm trying to insert the contents of the two divs into a single input field in a form.
This is what I have so far but at the moment the only field that copies over when the onclick occurs is the edit1 div contents.
any help would be greatly appreciated.
The JAVASCRIPT:
<script language="javascript" type="text/javascript">
function copyText2() {
var output = document.getElementById("edit1","edit2").innerHTML;
document.getElementById("user-submitted-tags").value = output;
}
</script>
The HTML:
<div id="edit1">foo</div>
<div id="edit2">bar</div>
<form>
<input class="usp_input" type="text" name="user-submitted-tags" id="user-submitted-tags" value="">
<input onClick="copyText2()" class="usp_input" type="submit" name="user-submitted-post" id="user-submitted-post" value="Submit Post">
</form>
Get the two contents separately, and then add them.
var output1 = document.getElementById("edit1").innerHTML;
var output2 = document.getElementById("edit2").innerHTML;
document.getElementById("user-submitted-tags").value = output1 + " " + output2;
Change
var output = document.getElementById("edit1","edit2").innerHTML;
into
var output = document.getElementById("edit1").innerHTML + document.getElementById("edit2").innerHTML;
That should work.
You should copy them one at a time and then concatenate
function copyText2() {
var output = "";
output += document.getElementById("edit1").innerHTML;
output += document.getElementById("edit2").innerHTML;
document.getElementById("user-submitted-tags").value = output;
}
document.getElementById("") is only using the first id string you give it. It doesn't accept multiple ids. From the Mozilla Dev docs:
id is a case-sensitive string representing the unique ID of the
element being sought.
Just have output grab the content from the first id, then from the second and append them together.
I have snippet of HTML in a string like this:
var htmlString = '<input type="text" id="someID" name="someID">';
How do I, with jQuery, set its value so that the HTML ends up like this:
'<input type="text" id="someID" name="someID" value="newValue">';
Thanks,
Scott
$(htmlString).attr("value", "newValue");
But this will return jQuery object, not string. You can add it to DOM.
$(htmlString).attr("value", "newValue").appendTo("body"); // you can give any element instead of body
EDIT :
You can use #idor_brad's method. That is the best way or
var htmlString = '<input type="text" id="someID" name="someID">';
var $htmlString = $(htmlString);
$htmlString.attr("value1", "newValue1");
$htmlString.attr("value2", "newValue2");
$htmlString.attr("value3", "newValue3");
console.log($htmlString.get(0).outerHTML);
or
var htmlString = '<input type="text" id="someID" name="someID">';
var $htmlString = $(htmlString);
$htmlString.attr("value1", "newValue1");
$htmlString.attr("value2", "newValue2");
$htmlString.attr("value3", "newValue3");
console.log($("<div>").append($htmlString).html());
You would first need to add your element to the DOM (ie to your web page). For example:
$(".container").append(htmlString);
Then you can access your input as a jquery object and add the value attribute like so:
$("#someID").val("newValue");
-- See Demo --
You just want to manipulate the string, right? There are a lot of ways to skin this cat, but
var newString = htmlString.replace('>', ' value="newValue">');
After the dom ready, append your input to body and then grab the input with id = "someID" and set its value to newValue
$(document).ready(function(){
$("body").append(htmlString);
$("#someID").val("newValue");
});