Put javascript data into a form - javascript

I have the following javascript code:
game.bind('gameover', function(seconds) {
setTimeout(function() {
var rank = game.getRank(seconds);
scorecard.find('.time').text(seconds + ' sec');
scorecard.find('.rank').text(rank[0]);
scorecard.find('.byline').text(rank[1]);
...more code
In the following div this data is displayed (so the js script is working):
<div class="inner">
<h3>Nice job! Your time:</h3>
<h1 class="wobble time"><!-- 15 seconds --></h1>
<h2 class="rank"><!-- Friendly Mallard --></h2>
<h3 class="byline"><!-- (That's pretty good) --></h3>
</div>
Now I want to put the results also in a form so I can post it to the a database (mysql). So I've added a form and put it in the same div:
<form id="form" action="updatescore.php" method="post">
<input type="text" id="time" name="time" value="" />
<input type="text" id="rank" name="rank" value="" />
<input type="text" id="byline" name="byline" value="" />
</form>
Now in the JS I've copied the lines (e.g. scorecard.find('.time').text(seconds + ' sec');) and changed it to look for the id, so . becomes # and passed it in the js like:
scorecard.find('.time').text(seconds + ' sec');
scorecard.find('#time').text(seconds + ' sec');
etc
So this should work I think, but the form inputs stay empty. What am I doing wrong?
Kind regards,
Maurice

If you are just looking to move js variables into your database via updatescore.php you don't need to use a form at all! You can do it with AJAX.
var scoreData = {
time : time,
rank : rank[0],
byline : rank[1]
};
$.post('updatescore.php', scoreData); //done!

Use val() instead of text() for setting the values

Related

Retrieving value of text input submits page with that value

I'm working on a HTML/JS method of capturing data within multiple input text boxes and running into a strange issue when trying to retrieve the values held within the inputs. I'll go ahead and post the code here before explaining my issue.
<div class="card-body">
<div id="manual-record-headers">
<b class="manual-record-header">Serial Number</b>
<b class="manual-record-header">Drive Health</b>
<b class="manual-record-header">Location</b>
<b class="manual-record-header">Username</b>
</div>
<div id="manual-record-table">
<div class="manual-record-row" id="manual-row-1">
<input type="text" class="form-control manual-record-input serial-num-input" placeholder="Serial number for drive...">
<input type="text" class="form-control manual-record-input drive-health-input" placeholder="Drive health state...">
<input type="text" class="form-control manual-record-input drive-location-input" onsubmit="return false;" placeholder="Storage location for drive...">
<input type="text" class="form-control manual-record-input username-input" placeholder="Check in username...">
<button class="delete-row"> <img src="/static/main/img/delete.png" width="34" height="34" /> </button>
</div>
</div>
</div>
for ( x=1; x < manual_record_count + 1; x++ ) {
temp_inventory_list = []
try {
serial = $('#manual-row-' + x + ' > .serial-num-input').val();
health = $('#manual-row-' + x + ' > .drive-health-input').val();
location = $('#manual-row-' + x + ' > .drive-location-input').val();
username = $('#manual-row-' + x + ' > .username-input').val();
}
catch(err) {
alert(err.message);
}
[program, drive_type, product_type] = get_data_from_drive_serial(serial)
temp_inventory_list = [serial, health, location, username, program, drive_type, product_type];
inventory_list.push(temp_inventory_list);
}
For some reason, on the third text input, where I am trying to retrieve the value of the ".drive-location-input", the page is being submitted with the value from that text input. So if I was to input a value of "333333333" into the .drive-location-input text input, the page would go from 127.0.0.1/main to 127.0.0.1/main/333333333. I should also note, that the page gets redirected/submitted before the try/catch and alert ever go off, so I can't see any possible errors that would be causing this.
As far as I can tell, there is no reason why this should be occurring, especially since the other 3 text inputs seem to be able to be retrieved with no issue. Is this an issue with the one text input itself, or should I be looking into why the page is even submitting with the value obtained in the first place?
Please let me know if any other info is necessary, and thanks in advance for any help.
Turns out that using "location" as a variable name is a big no-no. "location" returns the window elements location, and apparently results in a page redirect. So for anyone else that may see this issue in the future, look into if any variable names you are using have conflicts... Not a fun way to waste half a day!

JavaScript only changes text of first iteration with thymeleaf

I hope you are all well.
I have a school assignment, and I want to dynamically be able to change the name of a 'project'. This assignment is about projects. The way I've done it right now works with the first 'project' from a list of 'projects' iterated through with thymeleaf. I'm aware that what I've done right now is absolutely bad code behavior, but we have had no teaching in JS yet. But I really wanted this feature.
I don't know how to make this work for each project preview, right now it works for the first preview, but for the rest it just erases the project name from database. (see picture)
<div class="projects" th:each="projectNames : ${listOfProjects}">
<form action="deleteProjectPost" method="post">
<input type="hidden" th:value="${projectNames.projectID}" name="deleteID">
<input type="image" src="delete.png" alt="Submit" align="right" class="deleteProject" onclick="return confirm('Are you sure that you want to delete this project?')">
</form>
<form action="/editProjName" method="post">
<input type="hidden" name="projectID" th:value="${projectNames.projectID}">
<input type="hidden" id="oldName" th:value="${projectNames.projectName}">
<input type="hidden" id="newName" name="projectName">
<input type="image" src="edit.png" alt="Submit" onclick="change_text()" align="right" class="editProject">
</form>
<form action="/projectPost" method="post">
<input class="projectInfo" name="projectID" type="text" th:value="'Project No.: ' + ${projectNames.projectID}" readonly="readonly">
<input class="projectInfo" type="text" th:value="'Project name: ' + ${projectNames.projectName}" readonly="readonly">
<input class="projectInfo" type="text" th:value="${projectNames.projectStartDate} + ' - ' + ${projectNames.projectEndDate}" readonly="readonly">
<input type="submit" value="OPEN" class="openProject">
</form>
</div>
<script>
function change_text() {
var changedText;
var projectName = prompt("Please enter name of project:");
var oldName = document.getElementById("oldName").value;
if (projectName === null || projectName === "") {
changedText = oldName;
} else {
changedText = projectName;
}
document.getElementById("newName").value = changedText;
}
</script>
First form in HTML is the red cross to delete an entire 'project'. Second form is what is intended to change the name displayed on the 'project preview', but only works on first preview and deletes project name from the rest. Last form is the actual preview. I couldn't find another way to have multiple forms and do different POSTS while working with Java Spring and Thymeleaf.
My wish is to make the change_text() function work for each 'project preview'
Best regards!
function change_text(imageInput) {
var changedText;
var projectName = prompt("Please enter name of project:");
var oldName = imageInput.parentNode.querySelector('.old-name').value;
if (projectName === null || projectName === "") {
changedText = oldName;
} else {
changedText = projectName;
}
imageInput.parentNode.querySelector('.new-name').value = changedText;
}
<form action="/editProjName" method="post">
<input type="hidden" name="projectID" th:value="${projectNames.projectID}">
<input type="hidden" class="old-name" id="oldName" th:value="${projectNames.projectName}">
<input type="hidden" class="new-name" id="newName" name="projectName">
<input type="image" src="edit.png" alt="Submit" onclick="change_text(this)" align="right" class="editProject">
</form>
Ok so I made a few changes. First, notice the inputs with oldName and newName now have classes on them. These can be repeated. If you are not using the ids for anything other than the script, you should remove them. Otherwise if you have styling rules for them you should consider changing those CSS rules to use the class instead so you can remove the invalid repeating ids.
Secondly, the onlick of the image now passes in this. What that does is it passes in the actual input that the user clicked, so you have some context into which form element the user is interacting with.
Then looking at the logic, the method now accepts in imageInput which is the this from the onclick.
Using imageInput.parentNode we go up the DOM Tree to the parent element of the input, which is the form in this case. We can then turn around and use querySelector to find the other element in the form we want to manipulate. And it will only find the element in our particular form because that is what we are selecting off of.

Scraping data from input value

there is website which has:
<html>
<body>
<form action="/action_page.php">
First name: <div class="col-md-8 col-sm-8 col-xs-6"><strong><input type="text" class="no-style" value="John"></strong></div>
Last name: <div class="col-md-8 col-sm-8 col-xs-6"><strong><input type="text" class="no-style" value="Miller"></strong></div>
Email: <div class="col-md-8 col-sm-8 col-xs-6"><strong><input type="text" class="no-style" value="j.miller#gmail.com"></strong></div>
<input type="submit" value="Send">
</form>
</body>
</html>
Is it possible to scrape data from input value (John, Miller, j.miller#gmail.com) and show it in my page (maybe putting that site into iframe and scrape from it?) or maybe using something like:
// Get HTML from page
$.get( 'http://example.com/', function( html ) {
// Loop through elements you want to scrape content from
$(html).find("ul").find("li").each( function(){
var text = $(this).text();
// Do something with content
} )
} );
I don't know. I am not good with javascript. And there is bonus: input values on every refresh are different. Can I extract somehow data from 100 refresh or something? Thank you for any help!
i will assume that you need to get the data from the input element and then use it somewhere else in your site
you could easily do so using the jquery .val() function
here is some sample code
<form id="my-form">
name: <input type="text" id='test-input'/>
<input type="submit" />
</form>
<script>
var input;
$('#my-form').on('submit', function() {
input = $('#test-input').val();
});
</script>
you could then use the variable anyway you want, whether it is to cache data or for improving user experience
Get the value and var _value = $('#elementId').val(); and use it anywhere on the page $('#elementID').val(_value); or $('selector').text(_value);

Javascript link builder within HTML

I'm trying to build a... link builder to ease some of my day-to-day tasks. I can't make it work though, and would really appreciate some help:
<form target="">
ID one:
<input type="text" name="IDone" id="ID1">
ID two:
<input type="text" name="IDtwo" id="ID2">
<button value="go" id="myButton">build</button>
<script type="text/javascript">
document.getElementById("myButton").onclick = function () {
location.href =
"https://first.part.com/" + document.getElementById("ID1").value +
"?act=setsecond_part=" + document.getElementById("ID2").value;
};
</script>
</form>
The idea is very simple:
first field (ID one) gets the data that's put in it;
second field (ID two) gets the data that's put in it;
the "build" button actually goes to link that's comprised of https://first.part.com/ + + <?act=setsecond_part=> + <"ID2">.
Thank you for your assistance!
JPM
Delete a form tag and everything will be work fine :)

How To use Query string in java script?

I have Created calculator project. I have only two pages. Now my question how to pass input field value to another page? trying too many ways its Not Working.
What to do to pass input fields values from one page to another page?
My input fields code Looks Like
<p class="pull-right">DPA Minimum Buyer Contribution<br /></p>
<div class="row">
<div class="col-md-3">
</div>
<div class="col-md-6" style="padding-right:1%">
<input type="text" id="txtLocationContactName5" class="txt"/>
</div>
<div class="col-md-3" style="padding-left:0%">
Another page name default_results.php I have created input fields
<div class="col-md-5 padding-rht">
Minimum Buyer Contribution
</div>
<div class="col-md-2 padding-Zero">
<input type="text" id="txtCustomerName3" class="txt" />
</div>
I have tired in jQuery script
<script>
$(function () {
$("#btnQueryString").bind("click", function () {
var url = "default_results.php?id=" + encodeURIComponent($("#txtLocationContactName5").val()) + "&technology=" + encodeURIComponent($("#txtCustomerName3").val());
window.location.href = url;
});
});
</script
but Not working so how to pass value one page to other page ?
You're making life hard for yourself! A simple form is needed to help you pass data to another page :). See here for info on html Forms - http://www.w3schools.com/html/html_forms.asp
Here is a simple example for you:
<form action="page_2_link" method="POST">
<input type="text" name="field1" value="easy">
<input type="submit" name="button1" value="Submit">
</form>
Then on the second page you can do this to retrieve the form data:
<?php
$blah = $_POST['field1']; // this now has the posted fields value
?>
I have given the second page answer in PHP as you have used this as a tag for this question, so I hope you are using this or my answer won't work.

Categories