Solved: the answer was so simple. I needed to pass the variable into the function but the other coding was helpful. Thanks, all.
$array = array('a', 'b', 'c');
foreach($array as $key=>$info)
{
echo "<form action = 'form' method = 'post'>
<select name = 'choice' onChange = 'changeFunc()'>
<option value = 'first'>first</option>
</select>
<input type = 'submit' value = 'send'></form>
<div name = 'getID' id = '$key'> </div>";
}
function changeFunc()
{
var elements = document.getElementsByClassName('getID');
var key = elements[0].getAttribute('id');
}
So what's happening is that when I try to get the ID of the div that's in the loop, the default answer is the first loop. I'm not quite sure what the logic is to get individual divs that were created in the loop.
Since tagged with jQuery... I suggest you a change event handler for all select that has a name="choice" that will find the id of the div .getID withing its closest form.
$array = array('a', 'b', 'c');
foreach($array as $key=>$info){
echo "<form action='form' method='post'>
<select name='choice'>
<option value='first'>first</option> <!-- You probably need more than one option if you expect a change event ;) -->
</select>
<input type='submit' value='send'>
</form>
<div class='getID' id='$key'></div>"; // A class here instead of a name.
}
$(document).ready(function(){
$("select[name='choice']").on("change", function(){
var key = $(this).closest("form").find(".getID")[0].id
console.log("Select changed... Here is the key:", key)
});
});
// The same in plain JS
window.addEventListener("DOMContentLoaded", function(){
document.querySelectorAll("select[name='choice']").forEach(function(element){
element.addEventListener("change", function(){
var key = this.closest("form").querySelector(".getID").id
console.log("Select changed... Here is the key:", key)
});
});
});
I think,
document.getElementsByClassName('getID') => you get 3 elements
then elements[0].getAttribute('id') => you get first element
That is why you always get the first element id,
you can use this to get individual divs.
function changeFunc()
{
var element = this.closest("form").getElementsByClassName('getID');
var key = element.getAttribute('id');
}
Related
I have a drag and drop thing which uses clone. I am having a problem with the date clone though because of datepicker. Therefore, I need to make sure each cloned datepicker has a unique id. A cloned element looks like the following
<div data-type="date" class="form-group">
<label class="control-label col-sm-5" for="dateInput">Date Input:</label>
<div class="col-sm-3">
<input type="text" name="dateInput[]" class="form-control date_picker" id="dateInput">
</div>
</div>
So if I clone two date inputs, I will have two of the above. Now on submit, I clean all of the cloned html, doing things like removing the data-type. At this stage, if there is a cloned date input, I need to give it a unique id. At the moment I am doing this
$("#content").find(".form-group").each(function() {
var html = $(this).attr('class', 'form-group')[0].outerHTML.replace(/ data-(.+)="(.+)"/g, "");
var input = $(this).find('input');
var i = 0;
if(input.attr('id') == 'dateInput') {
alert("TEST");
input.attr("id",'dateInput' + i).datepicker();
i++;
}
console.log(html);
dataArray.push(html);
});
The TEST alert fires twice as it should do if I clone 2 date inputs. However, the id attributes do not seem to change when I output the html to the console. I have set up the following Fiddle to demonstrate that the id of the element is not changing.
Any advice on getting this to change appreciated.
Thanks
Try defining dataArray, i outside out submit event, .each() , using .map() , .get() , .attr(function() {index, attr}) , .outerHTML
$(function() {
// define `i` , `dataArray`
var i = 0, dataArray = [];
$('#content').submit(function(event) {
event.preventDefault();
$("#content").find(".form-group").each(function() {
var html = $(this).attr('class', '.form-group')[0]
.outerHTML.replace(/ data-(.+)="(.+)"/g, "");
dataArray.push($(html).map(function(_, el) {
// adjust `input` `id` here , return `input` as string
return $(el).find("input").attr("id", function(_, id) {
return id + (++i)
})[0].outerHTML
}).get()[0])
});
$("#output")[0].textContent = dataArray.join(" ");
console.log(dataArray)
});
});
jsfiddle https://jsfiddle.net/mLgrfzaL/2/
http://jsfiddle.net/4px4whk0/
I have two question
when first click the checkbox (a), the first console.log should be print the dom with empty data-selected-list attribute, I don't know why it filled what I click already (["a"]) ?
I have to set timeout wrap the container.attr('data-selected-list', selectedList); then it works like what I want.
when click other checkbox (b), I hope it will be ["a","b"] store in attribute. but it only store ["b"] , why?
I hope it can be solve by store data in html attribute not only store in jquery data api
$(document).ready(function() {
$('.container').on('click', 'input[type="checkbox"]', function() {
var container = $(this).closest('.container');
var input = $(this);
console.log(container);
var selectedList = container.data('selected-list');
if (selectedList == '') {
selectedList = [];
}
if (input.is(":checked")) {
selectedList.push(input.val());
}
console.log(selectedList);
selectedList = JSON.stringify(selectedList);
container.attr('data-selected-list', selectedList);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="container" data-selected-list="">
<input type="checkbox" value="a">a
<input type="checkbox" value="b">b
<input type="checkbox" value="c">c
</div>
You have several mistakes:
if you want to print the results of your array before you change it, then move the console.log call to before you push to the array
you were using attr and data interchangeably. These do two different things. attr stores the data in the DOM and data is a jquery method that stores the data somewhere within jquery itself.
finally, if you're using attr you need to do JSON.stringify to serialize your array before storing it (which you did do correctly) but when you pull the data out of the DOM you have to convert it back to an array with JSON.parse
jquery's attr returns undefined for an undefined DOM tag, not empty string
the right solution with these problems fixed is:
$(document).ready(function() {
var container = $('.container');
container.on('click', 'input[type="checkbox"]', function() {
var input = $(this);
console.log(container);
var selectedList = container.attr('data-selected-list');
if (!selectedList) {
selectedList = [];
}else{
selectedList = JSON.parse(selectedList);
}
console.log(selectedList);
if (input.is(":checked")) {
selectedList.push(input.val());
}
selectedList = JSON.stringify(selectedList);
container.attr('data-selected-list', selectedList);
});
});
here's a fiddle: http://jsfiddle.net/yLz6uv1q/
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
I have a form which is largely populated by checkboxes. The checkboxes each have an ID "value" that corresponds to an item within a javascript array. The array items hold some text that will populate a textarea.
I would like to include some dropdown boxes to clean up the site; however, I cannot seem to assign an array ID to the dropdown options? Can this be done in a selectbox option? Is there a workaround to simulate a selectbox without using the tab?
My html is basically:
<div>
<input type=checkbox id=array1 name=textArray></input>
<input type=checkbox id=array1 name=textArray></input>
<input type=checkbox id=array1 name=textArray></input>
...
<select><option 1><option 2>...</select>
</div>
<div>
<form>
<textarea id=outPut></textarea>
</form>
</div>
And my js is:
var textArray = {
array1: 'some text here',
array2: 'some more text',
array3: 'some other text',
...
array90: 'the last text'
};
// variable assigned to chosen item
var selectedInputs = document.getElementsByName("textArray");
for (var i = 0; i < selectedInputs.length; i++) {
selectedInputs[i].onchange = function() {
chosenItem = this;
printText();
};
}
// Script to add items to the Comments section text area
var mytextbox = document.getElementById('outPut');
var chosenItem = null;
function printText(){
if(chosenItem !== null){
mytextbox.value += textArray[chosenItem.id] + "";
// resets the radio box values after output is displayed
chosenItem.checked = false;
// resets these variables to the null state
chosenItem = null;
}
}
How can I associate an item in my js array with one of the selectbox choices?
I found it very difficult to understand what you're asking but I threw this together and hopefully it'll be helpful.
Important bit is
var selectNode = document.getElementById('select'); // <select id="select">
selectNode.onchange = function () {
if (selectNode.selectedIndex !== 0) {
chosenItem = selectNode.options[selectNode.selectedIndex];
selectNode.selectedIndex = 0;
printText();
}
}
and not to use the id attribute for what you're doing (I used data-i).
I'd also like to say that if you're cleaning up code this would be a good time to strongly reconsider how you're passing variables between functions; setting a value in the global namespace and relying on it in the next invocation is just asking for trouble (race conditions, conflicts with other bits of code, etc).
<option value="whatever">1</option> This has been part of HTML from the beginning.
I'm trying to get the value in my input field to be put into my post statement to be sent to my php file to update the record without reloading the page. It works fine with static information that I put in but when I want to select what I have typed in the input box, i can't get it to work. Nothing happens.
<script src="../jquery.js"></script>
<script type="text/javascript">
function editItem() {
catno = $("#catno").attr('value');
id = $("#id").attr('value');
$.post('writeToDB.php', {
id: id,
catno: catno
});
}
</script>
</head>
<body>
<form id="foo">
<input type="hidden" value="<?php echo $row_Recordset1['ID']; ?>" name="id"
id="id" />
<input type="text" value="<?php echo $row_Recordset1['CAT_NO']; ?>" name="catno"
id="catno" onchange="editItem();" />
</form>
I'm new to this javasrcipt world and jquery but I'm at the piont of pulling my hair out. I'm probably doing something really stupid
Thanks
Change
catno = $("#catno").attr('value');
id = $("#id").attr('value');
to
var catno = $("#catno").val();
var id = $("#id").val();
Use .val() to retrieve the value of an input.
You should also prefix your locally declared variables with var - this question/answer has a good explanation why
call val() method
id = $("#id").val();
val() method get the current value of the first element in the set of
matched elements
so your code will be
function editItem() {
var catno = $("#catno").val();
var id = $("#id").val()
$.post('writeToDB.php', {
id: id,
catno: catno
});
}
Use .val() :
http://api.jquery.com/val/