Using Javascript to pass an input value as a variable - javascript

I'm using JavaScript to try and pass the value of a hidden input field as a variable into the url path below, but when I inspect the code, I'm seeing 'undefined' where I want the variable to be.
I would really like to get this issue solved. Any idea why the value is 'undefined' instead of the value of the hidden input field?
var userID = "";
userID = $('#userID').val();
document.write("<input type='hidden' id='userID'>");
document.write("<a href='http://sample/folder/" + userID + "/Documents/Forms/All.aspx'><li>test</li></a>");

Your javascript can't find the value because your html is not created.
Try to create it, before getting the value.
document.write("<input type='hidden' id='userID' value='user1234'>");
var userID = "";
userID = $('#userID').val();
console.log(userID);
document.write("<a href='http://sample/folder/" + userID + "/Documents/Forms/All.aspx'><li>test</li></a>");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

You're getting undefined because the input field doesn't have any value. Make sure you set a default value to the field so that even if nothing is entered into the field, you can still extract a value.
<input type='hidden' id='userID' value="defaultText"/>
Reference (JSFiddle): https://jsfiddle.net/e7zkhhny/
Side-note: It's usually a good idea to put a placeholder on an input field.

You're trying to retrieve a value from an element that does not yet exist on the page. It will exist only after this statement runs document.write("<input type='hidden' id='userID'>");
To work around this,
1) Make sure that the javascript runs only after the hml loads using a $( document ).ready(function() {
$( document ).ready(function() {
var userID = ""
userID = $('#userID').val();
$('#link').attr("href", "http://sample/folder/" + userID + "/Documents/Forms/All.aspx");
}
2) Place the following html on your site:
<input type='hidden' id='userID' value="0">
<a id='link' href=''><li>test</li></a>

Related

Getting elements ID after created dynamicly by ajax via 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();'>

Unable to get hidden form value into javascript variable

I have a form with several fields. The value of one of the hidden fields is passed in the URL along with some other input values like this:
example.html#firstname=Homer&lastname=Simpson&itype=TARGET
I have a javascript that parses the URL and that is populating the form just fine. The output of the form contains all of the values passed from the url, so I know the variable are getting passed to the form fields.
My issue is - I want to be able to setup an if statement to change the text of one of the headings based on the value of itype.
Here's my code:
var itypestuff = document.getElementById("itype").value;
document.write ("<p>The value of the variable is " + itypestuff.value + "</p>");
if( itypestuff == "TARGET" ){
document.write("This is the target");
}
else{
document.write("This is not the target");
}
I added the first document.write statement as a debug and it's coming back with: The value of the variable is undefined
Here's what the itype field variable looks like:
<input type="hidden" name="itype" id="itype" value="">
Any ideas how I can get the variable from the URL into my javascript variable so I can do my if statement?
Change :
document.write ("<p>The value of the variable is " + itypestuff.value + "</p>");
To
document.write ("<p>The value of the variable is " + itypestuff + "</p>");
OR
Change
var itypestuff = document.getElementById("itype").value;
To
var itypestuff = document.getElementById("itype");
// And
if( itypestuff.value == "TARGET" ){ //...
EDIT
You have to change your html like that :
<input type="hidden" name="itype" id="itype" value="<?= htmlspecialchars($_GET['itype']); ?>">
And call : example.php?firstname=Homer&lastname=Simpson&itype=TARGET

How to grab value of read-only text field and use in angular js result

I have a textfield that is read only and pulling it's value from the query string. I can't get the value set in an output of javascript when bound with AngularJS.
<input type="text" class="form-control accountNumber" name="accountNumber" id="accountNumber" ng-model="accountNumber" ng-controller="main" data-placement="top" readonly>
function main($scope) {
var url = window.location.href;
var accountId = url.substr(url.indexOf("=") + 1);
$scope.accountNumber = accountId;
}
The account number needs to be placed into the "publisherId" field within the resulting javascript:
<script type="text/javascript" src="//cdnstatic.domain.com/"></script>
<script type="text/javascript">
window.addEventListener("load", function(e) {
var playerH = new Player({
adTag:"{{adTag}}",
fontElClass:"{{fontTag}}",
playerClass:"{{playerClass}}",
publisherId: "{{accountNumber}}"<===NEEDS TO BE REPLACED WITH VALUE FROM READ ONLY FIELD
});
});
</script>
To clarify:
1) function main($scope){} grabs the URL (which is also displayed in the textfield which is readonly), does some work on it and the value is stored in accountId.
2) That value is then supposed to be set in $scope.accountNumber, and used in the "publisherId:" field.
The resulting JavaScript is displayed to the user as text(not to be run on the page), and should have the {{accountNumber}} replaced with the value of the accountId.
The issue is that when the field is read only, its not showing the account number. It is also not setting the value in the publisherId field.
Here's my plnkr : Link,
I think your problem is that your controller is not defined for the entire view, just for your input.

jQuery selector by form index and input name

Take the following page with two forms with different classes but each form has an input with the same name.
<form class='first_form'>
<input name='test' value='1' />
</form>
<form class='second_form'>
<input name='test' value='3'/>
</form>
I can get the form index and I know the name of the input but I do not know the index of the input.
Is there a way to chain a selector with the form index and the input name to get the value?
I have tried chaining but nothing seems to work
var inputName = 'test';
Var formIndex = 1;
$('*[name="' + inputName + '"]' +' ' + '$("form").eq(' + formIndex + ')').val();
FIDDLE
var formIndex=0;
var inputName="txtbox";
vall= $("form:eq("+ formIndex+") input[name= "+ inputName +" ]").val();
alert(vall);
your order was wrong
Untested, but could you do:
$('form:nth-of-type(1) input[name="test"]').val();
$("form:nth-child("+formIndex+") input[name='"+inputName+"']").val();
You could do in a more clever way:
var fieldName = 'test';
var formId = '.first_form'
$('form'+formId+' input[name='+fieldName+']).val()
Instead of index, use named selectors, like id or class. It will help you in the future find the correct form (when you will have more than 5, it will be hard to count witch one you are looking at :) )
But that is too complex:)
I would propose something like this:
var currentForm = $('form'+formId);
currentForm//here you can put a log into console if element has not been found and find that bug sooner.
currentForm.find('input[name='+fieldName+']').val()
You can access the form's element directly within the DOM using either of:
document.forms[formIndex]
document.forms[formName]
You can then reference an input element by name using:
document.forms[formIndex][inputName]
document.forms[formName][inputName]
Then just wrap it in $(...) to get yourself a jQuery collection. In your case:
var inputName = 'test',
formIndex = 1;
$(document.forms[formIndex][inputName]);
I imagine this is by far the most performant way, and it's readable too.
To add a little detail, document.forms is an HTMLCollection of all HTMLFormElements within a document. And given any HTMLCollection or HTMLFormElement you can access named elements within them as properties.

Always returns a undefined value

I am using jQuery to send Ajax request to the server to save the values being input in the form. Below the section where I am stuck. The HTML is as
<span class="no-margin multiple Date_Off" style="margin-left: 104px;">
<input type="text" value="" /><input type="text" />
<input type="text" value="-" /><input type="text" />
<input type="text" /><input type="text" value="-" />
<input type="text" /><input type="text" /><input type="text" />
<input type="text" />
</span>
I have tried using jQuery to send the request. What I want to do is something like this
I want to save the values from the form, to the same Column_Name that the input fields have. In the multiple input fields I am not using input names. Instead I am using a classname which is identical to the Column_Name in the database.
For that, I am using $(this).parent().attr('class');. If I use this in an alert, it gives me the result without error. But if I use it in the code, it gives me undefined.
I want to append each input's value to the string to save it as a single string.
Here is what I tried so far
var input = $('input');
input.change(function () {
// Input click function...
if ($(this).parent().attr('class')
.replace(' multiple ', '')
.replace('no-margins', '') == 'Date_Off') {
// Date Time for the office work!
var value = '';
value = $(this).parent().find('input').each(function (index, ele) {
value += ele.val();
});
send_request('Date_Off', value);
// Below is the else condition, to execute only when the input is single
// Like a single string input and not like the one in image
// That's why I am using attr('name') for that.
} else {
send_request($(this).attr('name'), $(this).val());
}
});
But what it returns is always a undefined in the Query structure. Here is the function for that
function send_request(input_name, value) {
$.ajax({
url: '/ajax_requests/save_form',
data: 'input_name=' + input_name + '&form_id=' +
$('input[type=hidden]').val() + '&value=' + value,
error: function () {
$('.main-content').append(
'There was an error in request.
Please contact your website Developer to fix it.'
);
},
success: function () {
}
});
}
Image for the code execution
The input in focus was 1. Date. And the console shows the Internal Server Error. Because jQuery sent the request with input_name=undefined which is not a Column_Name.
I have created a (Mini) fiddle for that: http://jsfiddle.net/afzaal_ahmad_zeeshan/EHWqB/
Any help here?
For the fiddle that you posted, there were two errors. The first was you were calling ele.val(), but ele in this context is not a jQuery object - so you need to get the value property off of it. The second is that the jQuery each function operates on an array of objects and it's return value is that array of objects. You don't want your value, which should be a string, to be accepting that return value. Here is an updated, working fiddle
input.change(function () {
// Input click function...
var value = '';
$(this).parent().find('input').each(function (index, ele) {
value += ele.value;
});
send_request('Date_Off', value);
});
In this line you're trying to get the name of the input
send_request($(this).attr('name'), $(this).val());
I don't see a "name" attribute anywhere in your code, I think what you want is to get the class of the parent instead?
send_request($(this).parent().attr('class'), $(this).val());

Categories

Resources