Getting elements ID after created dynamicly by ajax via JAVASCRIPT - javascript

in the Name of God
hello.
I have a page that calls another page [answr.php] and it returns some objects like <input type=number>.
the problem is that I create those objects with a dynamic name. so I do not know the name of those objects. how can I guess them?
here is a simple code as like as my code:
Page 1:
I used a part of this function to separate the data in the object's ID.
this func is not important and just shows how can I separate my data from an object's ID
<script language="javascript">
function checknumber(theid){
.
.
.
var strObjName = theid.id.toString();
var strDateExt = strObjName.substring(5, 13);
var strIndexExt = strObjName.substring(13, 14);
document.getElementById("testOut").innerHTML = "Object's Name >" + theid.id.toString();
document.getElementById("testOut").innerHTML += "</br> the Date >" + strDateExt;
document.getElementById("testOut").innerHTML += "</br> the Index >" + strIndexExt;
}
and this is ans.php that answers over ajax and creates objects dynamicly:
$strShrtDate=sAddDateNoSlash($strDate,1);//this func returns a date string without slashes like 20161213
$strIdNumber="numId".$strShrtDate."0";
$strOut="<input id=$strIdNumber type='number' onchange = 'checknumber($strIdNumber);'>";
echo $strOut;
echo "<input name='btnSaveTmrow' type='button' value='Save' onClick='fnSaveTmrow();'>";
this creates a number object with the name "numId201612130" and a button.
that code creates a HTML tag like this:
<input type="number" is="numId201612130" onchange = 'checknumber(numId201612130);'>
<input name='btnSaveTmrow' type='button' value='Save' onClick='fnSaveTmrow();'>
numId sayes it is a number input and it's data is for date 2016/12/13 and the special code is 0.
Now I want to get the names like that [ numId201612130 , numId201612131 , numId201612140 , numId201612141 ,...] for processing some thing and insert into DataBank. how can I do it?
this is my fnSaveTmrow() function is JS:
function fnSaveTmrow(){
url = "SaveTmrow.php";
var vars = "mID="+i_ID+"&tmrowDate="; // <-- I want to send that data here to send by ajax again after that 'ans.php' code who dynamicly created the number input tag
fnDoAll(); // this is ajax code
}
I want to send the date inserted in the objects IDs and their value Like this:
var strObjName = document.getElementById("numId201612130").toString();
var strDateExt = strObjName.substring(5, 13); // contains 20161213
var strIndexExt = strObjName.substring(13, 14); // contains 0
var value = document.getElementById("numId201612130").value;
but I do not have munId201612130 ID because it created dynamicly and I have to retrive it dynamicly too.
I may have a function to returns me those IDs like munId201612130 or munId201612141 or munId201612152

Use document.querySelectorAll to get a list of every <input type="number"> that has an id.
var inputs = document.querySelectorAll('input[type=number][id]')
Then, call Array#map on this list to convert each element to its id:
function getAllDynamicIds() {
var inputs = document.querySelectorAll('input[type=number][id]')
return [].map.call(inputs, function (e) {
return e.id
})
}
console.log(getAllDynamicIds())
<input type="number" id="numId201612130" onchange = 'checknumber(numId201612130);'>
<input type="number" id="numId201612131" onchange = 'checknumber(numId201612131);'>
<input type="number" id="numId201612140" onchange = 'checknumber(numId201612140);'>
<input name='btnSaveTmrow' type='button' value='Save' onClick='fnSaveTmrow();'>

Related

Passing Variables Between Javascript and Python

I am attempting to pass the value of an integer from within a javascript function to a server side python script. I have tried to find a way to pass this value directly from the javascript to python but have not yet been successful, so instead I have tried to create a hidden element which contains the value of my int within my html form with the javascript function. Then using the action 'POST' with the Python Bottle framework I have tried to copy the value to my python script. However, the int is being processed as being of NoneType, rather than an int, and so I cannot use it within the processing script. The part of my JS function which creates the element with the int named instance is as follows
function newItem(){
instance++;
var oldInput = document.getElementById("itemInfo");
var parent = oldInput.parentNode;
var newDiv = document.createElement("div");
var item = document.createElement("INPUT");
var qty = document.createElement("INPUT");
var color = document.createElement("INPUT");
var count = document.createElement("HIDDEN");
item.name = "item" + instance;
qty.name = "qty" + instance;
color.name = "color" + instance;
count.value = instance;
newDiv.appendChild(item);
newDiv.appendChild(qty);
newDiv.appendChild(color);
newDiv.appendChild(count);
The HTML form with the 'POST' method
<form method ="post" class="form" action = "/newguest" method = 'post'>
Name: <input type="text" name="name"/>
<p>Item: <input type="text" name="item"/>
Qty: <input type="text" name="qty"/>
Color: <input type="text" name="color"/></p>
<div class="itemInfo" id="itemInfo"></div>
<input type ="button" value="Add Item" onclick="newItem();"/>
<p>Phone: <input type="text" name="phone"/>
Email: <input type="text" name="email"/>
Artwork: <input type="file" name="file"/>
<p>Quote: <input type="text" name="quote"/></p>
</p>
<p>Notes: <textarea cols="40" rows="10"></textarea>
</p>
<input type="submit" value='Add Order'/>
</form>
And finally the python script on the server side
#bottle.route('/newguest', method = 'POST')
def insert_newguest():
name = bottle.request.forms.get("name")
email = bottle.request.forms.get("email")
item = bottle.request.forms.get("item")
qty = bottle.request.forms.get("qty")
color = bottle.request.forms.get("color")
count = bottle.request.forms.get(count)
itemDict = dict()
qtyDict = dict()
colorDict = dict()
for num in range(1, count):
itemkey = "item" + str(num)
qtyKey = "qyt" + str(num)
colorKey = "color" + str(num)
itemDict[itemKey]= bottle.request.forms.get("item"+str(num))
qtyDict[qtyKey] = bottle.request.forms.get("qty"+str(num))
colorDict[colorKey] = bottle.request.forms.get("color"+str(num))
When attempting to add information with the 'POST' method, I receive the following error:
You are probably getting this message because your hidden field hasn't been created correctly.
Firstly, I can't see you actually adding the newDiv to the DOM in your code above.
Secondly - is the HTML form you have provided hard coded? If so then why are you hardcoding a form and then creating the fields again in javascript? This seems a bit weird.
Thirdly and most importantly, as a hidden field is just an <input>, you need to replace
var count = document.createElement("HIDDEN");
With:
var count = document.createElement("INPUT");
count.setAttribute('type', 'hidden');
count.setAttribute('name', 'count');
count.setAttribute('value', my_count_variable);
See this answer and an example jsFiddle. Now when you submit the form your count field should be populated in the Python script.
As an aside, this kind of request is often handled by AJAX. The idea is the same its just that you don't need to refresh the browser to send your count to the Python server. You can see an example of how to do this without jQuery here.

How can I create dynamic controls and put their data into an object?

I created a div and a button. when the button clicked, there will be a group of element(included 1 select box and 2 text inputs) inserted into the div. User can add as many group as they can, when they finished type in data of all the group they added, he can hit save button, which will take the value from each group one by one into the JSON object array. But I am stuck in the part how to get the value from each group, so please help, thank you.
The code for the div and the add group button function -- AddExtra() are listed below:
<div id="roomextra">
</div>
function AddExtra() {
$('#roomextra').append('<div class=extra>' +
'<select id="isInset">' +
'<option value="Inset">Inset</option>' +
'<option value="Offset">OffSet</option>' +
'</select>' +
'Length(m): <input type="text" id="insetLength">' +
'Width(m): <input type="text" id="insetWidth">' +
'Height(m): <input type="text" id="insetHeight">' +
'</div>');
}
function GetInsetOffSetArray (callBack) {
var roomIFSDetail = [{
"IsInset": '' ,
"Length": '' ,
"Width": '' ,
"Height": ''
}];
//should get all the value from each group element and write into the array.
callBack(roomIFSDetail);
}
This should just about do it. However, if you're dynamically creating these groups, you'll need to use something other than id. You may want to add a class to them or a data-* attribute. I used a class, in this case. Add those classes to your controls so we know which is which.
var roomIFSDetail = [];
var obj;
// grab all of the divs (groups) and look for my controls in them
$(.extra).each(function(){
// create object out of select and inputs values
// the 'this' in the selector is the context. It basically says to use the object
// from the .each loop to search in.
obj = {
IsInset: $('.isInset', this).find(':selected').val() ,
Length: $('.insetLength', this).val() ,
Width: $('.insetWidth', this).val() ,
Height: $('.insetHeight', this).val()
};
// add object to array of objects
roomIFSDetail.push(obj);
});
you'd better not to use id attribute to identity the select and input, name attribute instead. for example
$('#roomextra').append('<div class=extra>' +
'<select name="isInset">' +
'<option value="Inset">Inset</option>' +
'<option value="Offset">OffSet</option>' +
'</select>' +
'Length(m): <input type="text" name="insetLength">' +
'Width(m): <input type="text" name="insetWidth">' +
'Height(m): <input type="text" name="insetHeight">' +
'</div>');
}
and then, usr foreach to iterate
$(".extra").each(function() {
var $this = $(this);
var isInset = $this.find("select[name='isInset']").val();
var insetLength = $this.find("input[name='insetLength']").val();
// ... and go on
});
A common problem. A couple things:
You can't use IDs in the section you're going to be repeating, because IDs in the DOM are supposed to be unique.
I prefer to use markup where I'm writing a lot of it, and modify it in code rather than generate it there.
http://jsfiddle.net/b9chris/PZ8sf/
HTML:
<div id=form>
... non-repeating elements go here...
<div id=roomextra>
<div class=extra>
<select name=isInset>
<option>Inset</option>
<option>OffSet</option>
</select>
Length(m): <input id=insetLength>
Width(m): <input id=insetWidth>
Height(m): <input id=insetHeight>
</div>
</div>
</div>
JS:
(function() {
// Get the template
var container = $('#roomextra');
var T = $('div.extra', container);
$('#addGroup').click(function() {
container.append(T.clone());
});
$('#submit').click(function() {
var d = {};
// Fill d with data from the rest of the form
d.groups = $.map($('div.extra', container), function(tag) {
var g = {};
$.each(['isInset', 'insetLength', 'insetWidth', 'insetHeight'], function(i, name) {
g[name] = $('[name=' + name + ']', tag).val();
});
return g;
});
// Inspect the data to ensure it's what you wanted
debugger;
});
})();
So the template that keeps repeating is written in plain old HTML rather than a bunch of JS strings appended to each other. Using name attributes instead of ids keeps with the way these elements typically work without violating any DOM constraints.
You might notice I didn't quote my attributes, took the value attributes out of the options, and took the type attributes out of the inputs, to keep the code a bit DRYer. HTML5 specs don't require quoting your attributes, the option tag's value is whatever the text is if you don't specify a value attribute explicitly, and input tags default to type=text if none is specified, all of which adds up to a quicker read and slimmer HTML.
Use $(".extra").each(function() {
//Pull info out of ctrls here
});
That will iterate through all of your extra divs and allow you to add all values to an array.

Creating a Pass Fail Input Function

I am creating a test form. I have created a form with a list of steps to test.
Instead of every item on the list needing:
<input type="radio" name="step1">Pass<input type="radio" name="step1">Fail
I wanted to create a function so I could just call it every time to create it.
This is my function so far:
function createPassFail(name)
{
var Pass = document.createElement('input');
Pass.type = "radio";
Pass.name = name;
document.getElementById("Pass").innerHTML = "Pass";
var Fail = document.createElement('input');
Fail.type = "radio";
Fail.name = name;
document.getElementById("Fail").innerHTML = "Fail";
}
And then I call it with:
<li>Step One: Turn the TV On
<input id = "step1" onload="createPassFail(this.value)">
</li>
All this does is create a textbox which is not what I was going for. I am also not sure if onload is correct.
Instead of passing in the value to the function you should pass the id:
onload="createPassFail(this.id)"
// ^^
I say your event should be onblur because I don't think onload is the event handler you should be using. You can use my suggestion or maybe set up a button next to the text box which, when clicked (using onclick) does what you want.
Moreover, you haven't inserted the pass or fail elements into HTML. Try this:
document.body.appendChild(Pass);
document.body.appendChild(Fail);
This inserts the newly-created elements directly to the end of the body element. If you would like them to be child to some element therein, you would have to access the element with a suitable method. For example, with getElementById:
document.getElementById( element ).appendChild(Pass); // do the same for Fail
However, this can all be easily done with jQuery.
$(document).ready(function() {
function createPassFail(name)
{
$('body').append('<input type="radio" id="' + name + '">Pass');
$('body').append('<input type="radio" id="' + name + '">Fail');
}
$('#step1').ready(function() {
createPassFail(this.id);
});
});
Live Demo

array input text get value

i want to get input text value of array in javascript
this is my code :
Item : <input id="t_item" name="t_item[]" type="text" class="teks3">
Cost : <input id="t_cost" name="t_cost[]" type="text" class="teks3">
<input type="button" id="tb_more_item" class="add_file"/>
and the js code is :
$("input#tb_more_item").click(function(){
var new_file = $("
Item : <input id='t_item' name='t_item[]' type='text' class='teks3'/>
Cost : <input id='t_cost' name='t_cost[]' type='text' class='teks3'/>
");
$("div#div_item").append(new_file).fadeIn();
});
i try to get more item value with this code :
var item_value = [], cost_value = [];
$("input#t_item").each(function() {
$thisItem = $(this);
item_value = $thisItem.val();
});
$("input#t_cost").each(function() {
$thisCost = $(this);
cost_value = $thisCost.val();
});
alert(item_value +"-"+ cost_value );
the result is get the last value value i've typed in the input text.
does anyone have the solutions?
thanks
You're creating invalid html by appending elements with duplicate ids. Update the .each() selectors to use the name attribute instead.
Also, inside the .each() functions you are overwriting the array variables with the value of the current item - that is, the array gets thrown away and replaced with the value, which is why that variable holds only the last value after the .each() finishes. What you want to do is add the value of each input as a separate element in the array:
$('input[name="t_item\\[\\]"]').each(function() {
item_value.push(this.value);
});
And similar for t_cost.

How do I get a handle to a dynamically-generated field name in javascript?

I have a series of fields created dynamically based on database records. They will be named cardObject1, cardObject2, and so on for as many rows as necessary. I'm now trying to access a specific cardObject field in a function where the number is passed in, but am getting an error message.
The field looks like this:
<input name="cardObject241" value="2,$25.00,1" type="hidden">
The js code I'm using looks like this:
function deleteFromCart(id){
if (confirm("Are you sure you want to delete this item from your cart?")){
var voucherNbr = document.getElementById("voucherNbr").value;
var cardObjectArray = document.getElementById("cardObject"+id).value.split();
var amtToDelete = cardObjectArray[1];
alert("need to delete " + amtToDelete);
}
}
And the error I'm getting is
document.getElementById("cardObject" + id) is null
on this line:
var cardObjectArray = document.getElementById("cardObject"+id).value.split();
How can I get a handle to the cardObject field that ends with the number passed in as the id param?
You need to add an id="" attribute with the same name as the name attribute.
<input id="cardObject241" name="cardObject241" value="2,$25.00,1" type="hidden">
Firstly, your input field needs an id as well as a name, so it would look like this:
<input name="cardObject241" id="cardObject241" value="2,$25.00,1" type="hidden">
Secondly, if you have an object that may or may not exist, it's always a good idea to check for existence before you start manipulating properties:
var tempObj=document.getElementById("cardObject"+id)
if(tempObj) {
var cardObjectArray = tempObj.value.split();
...do your stuff with cardObjectArray....
}
You can use document.getElementsByName() or (cross-browser back to the Stone Age)
document.forms[formIndexOrName].elements["cardObject" + id].value.split(",")

Categories

Resources