First example:
var dbSelected = "File selected: ";
var filenamePanel = document.getElementById('filenamePanel');
filenamePanel.textContent = dbSelected + files[0].name;
var postLink = files[0].link;
document.getElementById('postLink').value = postLink;
var postName = files[0].name;
document.getElementById('postName').value = postName;
If I use <input type="hidden" name="postName" id="postName"> to send the value to another page via POST with PHP, it works.
Second example:
function onSuccessCallback(Blob){
document.getElementById('postName').textContent = Blob.filename;
document.getElementById('postLink').textContent = Blob.url;
document.getElementById('results').textContent = JSON.stringify(Blob);
};
Now, If I use <input type="hidden" name="postName" id="postName"> on the second example to send the 'postName' id value to another page, the value is empty.
What changes are necessary, on the second example, so that I can send the 'postName' id value to another page using a hidden <input> field?
Use .value instead of .textContent to store the data in the hidden input field:
document.getElementById('postName').value= Blob.filename;
Related
I want to extract the value from date field, but it doesn't work. I add the input this way:
var question0 = "<div id='0'><p>Please, enter the date: </p><br>"
+ "<input type=\"date\" id=\'contractdate\'></input><br></div>";
Here is how I tried to receive the value:
var text_Contract_Date = document.getElementById('contractdate').value;
//tried the code below, but didn't work
// var text_Contract_Date = document.getElementById('contractdate').valueAsDate;
// var text_Contract_Date = new Date(document.getElementById('contractdate').valueAsDate);
So, I want to get the value from input as a string, using pure JavaScript, because then it will be used to fill in the document.
Try this
var dateEntered = new Date(text_Contract_Date);
There is not enough information to resolve the issue, so I can only guess that you are probably inserting your variable into the DOM the wrong way.
If I call document.body.append(question0), only text is shown and not the tags.
Try moving content of question0 variable to your html file, then add onchange handler to your input, and also modify your .js file like below
function handleChange(event){
// here you can do whatever you want with the value of the input
alert(event.target.value)
}
<input type="date" id='contractdate' onchange="handleChange(event)"></input>
If you desperately want to create your HTML inside of Javascript, you have to do this like this:
// create div and assign id to it
const myDiv = document.createElement("div")
myDiv.id = '0'
// create p and set its contents
const myP = document.createElement("p")
p.textContent = "Please, enter the date: "
// create input, assign id to it and set its type to date
const myInput = document.createElement("input")
myInput.id = 'contractdate'
myInput.type = "date"
// put everything in your document
myDiv.appendChild(myP)
myDiv.appendChild(myInput)
document.body.appendChild(myDiv)
I want to read user input into a form back to them, sort of a confirmation before they send it in. I have some text elements on the page with their corresponding IDs. I would think that I just need to set the variables equal to the values of the input field, but when the function runs it just returns blank.
I have a function that sets the variables to the .value of that form input, but where I might be getting hung up is that there is no default value on the input field, I would think that the value is set after the user inputs something.
Example user inputs "John Doe" into field shouldn't that change the value of that field to "John Doe"?
var Phone;
document.getElementById('confirm-details').onclick = ConfirmDetails()
function ConfirmDetails() {
// Set variable to form input
Phone = document.getElementById("InputPhone").value;
// Change text element to variable
document.getElementById("BookingPhone").innerHTML = Phone;
};
Maybe I'm just confused about the .value attribute but I thought that the value on an input field should be what the user inputted.
This row
document.getElementById('confirm-details').onclick = ConfirmDetails()
should be
document.getElementById('confirm-details').onclick = ConfirmDetails
You don't want that document.getElementById('confirm-details').onclick references the result of the function ConfirmDetails (here void) but the function itself.
Instead of using .value, you need to be using .innerText
Phone = document.getElementById("InputPhone").innerText;
object.oninput = function(){
ConfirmDetails();
};
or, shorthand:
object.oninput = function(){ConfirmDetails()};
You should also use document.getElementById().innerHTML() to get the text
This worked just fine for me. I appreciate all the answers!
<script>
document.getElementById("confirm-details").addEventListener("click", function(){
document.getElementById("BookingName").innerHTML = document.getElementById("InputName").value;
document.getElementById("BookingEmail").innerHTML = document.getElementById("InputEmail").value;
document.getElementById("BookingPhone").innerHTML = document.getElementById("InputPhone").value;
document.getElementById("InputDay").innerHTML = document.getElementById("BookingDay").value;
document.getElementById("InputTime").innerHTML = document.getElementById("BookingTime").value;
document.getElementById("InputService").innerHTML = document.getElementById("BookingService").value;
document.getElementById("InputExtra").innerHTML = document.getElementById("BookingExtra").value;
});
</script>
Here is what I believe you are trying to accomplish:
function confirmDetails() {
// Set variable to form input
var phone = document.getElementById("inputPhone").value;
var confirmMsg = 'is ' + phone + ' correct?' + '<br> <input type="button" value="Yes" onclick="confirmed()"> ';
// Change text element to variable
document.getElementById("bookingPhone").innerHTML = confirmMsg;
};
function confirmed(){
alert('confirmed');
}
<input id="inputPhone" type="text" placeholder="input here">
<input type="button" onclick="confirmDetails()" value="Submit">
<br>
<span id="bookingPhone"></span>
When the button is clicked, it runs the function confirmDetails and sets the variable phone to the user's input. I set variable confirmMsg to the confirm message which reads back the user's input. I used a span with a unique ID and sent the variable confirmMsg to it.
I put the confirm message into a variable to make it more versatile, should you need it elsewhere.
I'm using serializeArray() to retrive the form attributes. When I try to get the attributes, I'm receiving name and value for all the fields.
I have checked the documentation https://api.jquery.com/serializeArray/. I understood it will return the name and value of all the fields.
Now I have few custom attributes for some fields. I want to retrieve them using those custom attributes.
How can i achieve this?
Here is my logic.
var data = $('form').serializeArray();
var newData = {};
var queue = {};
data.forEach(function(field) {
if( field.customField != undefined && field.customField.indexOf("true")>=0 ) {
queue[field.name] = frm.value
} else {
newData[frm.name] = frm.value;
}
});
I need to get that customField attribute, I'm adding that to the HTML field attribute.
May not be the best, but you can do like this.
Let's say you have set of text boxes, text areas and so on with custom data attributes in it. What I am doing here is adding a class to those fields that you need to get value / data attributes in it.
Let's take the following HTML as an example.
HTML
<form id="frm">
<input class="serialize" type="text" name="title1" value="Test title 1" data-test1="test AAA" data-test2="test BBB" /><br/>
<input class="serialize" type="text" name="title2" value="Test title 2" data-test1="test CCC" data-test2="test DDD" /><br/>
<textarea class="serialize" data-test1="textarea test 1">TEST 22 TEST 11</textarea>
<button id="btn" type="button">Serialize</button>
</form>
What I am doing here is iterating through fields which has class .serialize and putting value, name, data attributes and so on to an array.
jQuery
$(document).ready(function(){
$('#btn').on('click', function(e) {
var dtarr = new Array();
$(".serialize").each(function(){
var sub = new Array();
sub['name'] = $(this).attr('name');
sub['value'] = $(this).val();
//data attribute example
sub['data-test1'] = $(this).data('test1');
sub['data-test2'] = $(this).data('test2');
dtarr.push(sub);
});
// This will give you the data array of input fields
console.log(dtarr);
});
});
Hope this helps.
I'm trying to validate input from this form:
<form id = "mpath" name = "mpath" action = './../cgitest.cgi' method="POST" onsubmit = "return validateForm(this)">
Total Time (in ms): <input type = "text" name = "ttime">
Number of Cars (1-10): <input type = "text" name = "carnum">
Initial Speed (fps): <input type = "text" name = "initspeed"><br>
<!--extraRowTemplate will be repeated for every change in the accleration of the
head car -->
<p class = "extraRowTemplate" name = "extraRowTemplate">
Change:
<select name="change">
<option value="acc">Acceleration</option>
<option value="dec">Deceleration</option>
</select>
Start time: <input type = "text" name="starttime">
End time: <input type = "text" name="endtime">
Amount (in fps): <input type = "text" name="amount"><br>
</p>
<div id = 'container'></div>
<i class="icon-plus-sign"></i>Add Change<br>
<input type="submit" value="Load Head Car">
</form>
Using this function (I haven't written any of the actual validation):
<script type="text/javascript">
function validateForm(form){
var tt = document.forms[0].ttime.value;
var cn = document.forms[0].carnum.value;
var is = document.forms[0].initspeed.value;
var sta = form.elements[4].value;
console.log(tt);
console.log(cn);
console.log(is);
console.log(sta);
if(tt == ""){
alert("starttime must be filled out");
return false;
}
//return false;
}
</script>
But when I try to submit values, it only finds the values for ttime, carnum, and initspeed, and not the value of starttime, endtime, or amount. Also, the value of change is always "acc", even if I set it to "deceleration".
For those wondering why I don't simply remove extraRowTemplate, I need to have those input options in a nested section because I have an option to duplicate them.
I've tried to pass the form as an argument to the function (as shown) as well as just use document.forms[0] to access it. Neither produce the correct result.
Also, when I remove the .value from the form.elements[4].value and set:
var sta = form.elements[4];
The console prints out:
<input type = "text" name = "starttime">
Does anyone know how I can access the value of the nested inputs?
I suppose I should also say that the form works correctly in every other way, and when I send it to the cgitest.cgi, I can access all inputs. I just don't want to validate the inputs on the server side.
EDIT:
If instead of using an onsubmit function (validateForm in my case), I use an event listener:
<script type="text/javascript">
var button = document.querySelector('input[type=submit]')
button.addEventListener('click', function onClick(event) {
var ttime = document.querySelector('input[name=ttime]')
var carnum = document.querySelector('input[name=carnum]')
var initspeed = document.querySelector('input[name=initspeed]')
var change = document.querySelector('select[name=change]')
var starttime = document.querySelector('input[name=starttime]')
var endtime = document.querySelector('input[name=endtime]')
var amount = document.querySelector('input[name=amount]')
console.info('ttime', ttime.value)
console.info('carnum', carnum.value)
console.info('initspeed', initspeed.value)
console.info('change', change.value)
console.info('starttime', starttime.value)
console.info('endtime', endtime.value)
console.info('amount', amount.value)
event.preventDefault()
})
</script>
With the input ttime = 1, carnum = 2, initspeed = 3, change = "acc", starttime = 4, endtime = 5, amount = 6, I get the following console output:
(index):70 ttime 1
(index):71 carnum 2
(index):72 initspeed 3
(index):73 change acc
(index):74 starttime
(index):75 endtime
(index):76 amount
As can be seen, all values beyond initspeed (everything inside extraRowTemplate) are empty. Like I said before, they are not empty when sent to the form action url.
Can you try removing the extraRowTemplate and submit. If it's working, than you can try generating the elements inside with the different ids, because now you have duplicated items with no distinction.
You are currently accessing the elements in a bit of a roundabout way, using document.forms[0]. Also I don't see any code to get the value of the starttime input. You are testing tt in the if, but that was assigned the value of ttime.
document.querySelector
Might I suggest accessing the form elements by name directly, using document.querySelector? This method accepts a CSS selector and returns the first element that matches. Using a simple CSS3 selector we can select elements by name and assuming those names are unique on the page, we will get the right inputs. You could also use form.querySelector if the names are only unique within the form.
Example
var myInput = document.querySelector('input[name=ttime]')
I find document.querySelector and document.querySelectorAll (which gets all elements matching the CSS selector) very useful and use them all the time.
Runnable code snippet
Run this snippet and press the form submit button to print the values of the inputs. Try it and see how it works.
var button = document.querySelector('input[type=submit]')
button.addEventListener('click', function onClick(event) {
var ttime = document.querySelector('input[name=ttime]')
var carnum = document.querySelector('input[name=carnum]')
var initspeed = document.querySelector('input[name=initspeed]')
var change = document.querySelector('select[name=change]')
var starttime = document.querySelector('input[name=starttime]')
var endtime = document.querySelector('input[name=endtime]')
var amount = document.querySelector('input[name=amount]')
console.info('ttime', ttime.value)
console.info('carnum', carnum.value)
console.info('initspeed', initspeed.value)
console.info('change', change.value)
console.info('starttime', starttime.value)
console.info('endtime', endtime.value)
console.info('amount', amount.value)
event.preventDefault()
})
<form id = "mpath" name = "mpath" action = './../cgitest.cgi' method="POST" onsubmit = "return validateForm(this)">
Total Time (in ms): <input type = "text" name = "ttime">
Number of Cars (1-10): <input type = "text" name = "carnum">
Initial Speed (fps): <input type = "text" name = "initspeed"><br>
<!--extraRowTemplate will be repeated for every change in the accleration of the
head car -->
<p class = "extraRowTemplate" name = "extraRowTemplate">
Change:
<select name="change">
<option value="acc">Acceleration</option>
<option value="dec">Deceleration</option>
</select>
Start time: <input type = "text" name="starttime">
End time: <input type = "text" name="endtime">
Amount (in fps): <input type = "text" name="amount"><br>
</p>
<div id = 'container'></div>
<i class="icon-plus-sign"></i>Add Change<br>
<input type="submit" value="Load Head Car">
</form>
I can access the value of your "starttime" field in Firefox/Chrome/Opera using either
var sta = document.forms[0][4].value
or
var sta = document.forms[0].starttime.value
I was able to figure out what was going wrong. In my css I set:
.extraRowTemplate {
display: none;
}
which was preventing the input values from being sent. Once I removed this my problems went away. Setting "visibility : hidden" is a good alternative that allowed the values to be submitted and the template not visible.
Let's say I have this piece of code from first.html
<input type="text" id="name">
Go to next page
How can I make it that when you go to second.html, javascript alerts the value of [name] from first.html OR the html adds an h1 tag with the value of [name] from first.html
You can use document.getElementById() function to get input and access it's value property to read what was entered there.
The onclick attribute on your anchor element will execute a custom function which will take the href property of the anchor and append the url-encoded value of the input field.
Then it will go to that new URL.
The return false ensures that built-in href event does not execute.
function link(anchor) {
var name = document.getElementById("name").value
var url = anchor.href + "?name=" + encodeURIComponent(name);
window.location.href = url;
}
<input type="text" id="name">
Go to next page
To read the passed in variable on the receiving page, use the technique described in this SO post:
How can I get query string values in JavaScript?
you could use onclick function on anchor tag.
<input type="text" id="name">
<a onclick="goToNextPage()">Go to next page</a>
<script>
function goToNextPage()
{
var value = document.getElementById('name').value;
window.location.href="second.html?name="+value;
}
</script>
Or you could use form.submit() to post the form values to request.
As HTML is only markup language, not programming language. So, you would need either php/ javascript to fetch that value on second page.
function qs(search_for) {
var query = window.location.search.substring(1);
var parms = query.split('&');
for (var i=0; i<parms.length; i++) {
var pos = parms[i].indexOf('=');
if (pos > 0 && search_for == parms[i].substring(0,pos)) {
return parms[i].substring(pos+1);;
}
}
return "";
}
and then call that function in your second page as.
<script type="text/javascript">
document.write(qs("name"));
</script>