Showing information in text fields with JavaScript - javascript

I have two text fields in a form and a submit button. When the user clicks on in it must show a box message, containing the information user has provided and the current time.
How can I do this? Keep in mind that I'm a beginner with JavaScript.

You mean something like this?
<form onsubmit="formMessage(this);">
<p>First Name: <input name="firstname" id="firstname" /></p>
<p>Last Name: <input name="lastname" id="lastname" /></p>
<p><input type="submit" name="submit" value="Submit!" /></p>
</form>
function formMessage(frm)
{
var fn = frm.firstname.value;
var ln = frm.lastname.value;
var dt = new Date();
alert("You entered " + fn + " " + ln + " at " + dt + "!");
}
Demo: http://jsfiddle.net/EBKJ5/

You could do something like the following ( if your elements have id's on them ):
document.getElementById( "buttonId" ).addEventListener( "click", function() {
alert( document.getElementById( "formId" ).value + " " + new Date() );
}, false );

You can include a javascript file in your solution/html file and add a function that employs document.getElementById('nameofyourtextbox').value to retrieve the value and then use an alert box to display the values provided and then add the date in.
This function can then be called on the onclick event of your button.
example:
function buttonClicked()
{
var d = new Date();
var date = d.getDate();
var month = d.getMonth();
var year = d.getFullYear();
alert(document.getElementById('nameofyourtextbox') +", "+ document.getElementById ('nameofyour2ndtextbox') + ", "+ date +"/"+ month +"/"+ year);
}
Add the function to the onclick event of your button:
<...... onclick="buttonClicked();">
To add the .js file to your page:
<script type="text/javascript" src="nameofyourjsfile.js"></script>
The src attribute must be the path to where your .js file is stored.

Related

Validate form data before submit and based on the validation call another function using javascript

I am new to web development. I am building an application to log effort. Currently i am mandating the form elements. Need to check if all fields are populated and then export the form data to an excel.
I have written the below code, please do consider that i am a newbie into this before firing on me about the code ethics.
Currently i am not focusing on the CSS part, so i do not have a css file.
<html>
<head>
<script type="text/javascript" language="javascript">
function WriteToFile(passForm) {
var fso = new ActiveXObject("Scripting.FileSystemObject");
var fileLoc = "E:\\sample.csv";
var file = fso.openTextFile(fileLoc, 8, true, 0);
file.writeline(passForm.inputText.value + ',' +
passForm.timeSpent.value + ',' +
passForm.SystemDate.value + ',' +
passForm.UserName.value);
file.Close();
alert('File created successfully at location: ' + fileLoc);
}
onload = function systemDate() {
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth() + 1;
var yyyy = today.getFullYear();
if (dd < 10) {
dd = '0' + dd;
}
if (mm < 10) {
mm = '0' + mm;
}
var today = mm + '/' + dd + '/' + yyyy;
document.getElementById("date").value = today;
}
</script>
</head>
<body>
<p>Happily log your effort!</p>
<form>
Ticket Number : <input id="inc" type="text" name="inputText" required="true" size="20"><br> Effort(In Hours): <input id="tsp" type="text" name="timeSpent" required="true" size="20"><br> Date(Effor Put On) : <input id="date" type="text" name="SystemDate"
required="true"><br> Effort Logged By: <input type="text" name="UserName" value="Abrar" disabled="true"><br>
<input type="Submit" value="submit" onclick="WriteToFile(this.form)">
</form>
</body>
</html>
Please help me out in successfully validating all fields and exporting the data.
This is a much simpler code where i have marked field elements required but still the form data is getting exported even when the required fields are empty and in fact the validation is happening post export.
Try this - please note I have been pragmatic and used onload and form element access - that is because it will work in all browsers without loading things like jQuery etc. I have also not tested for valid date. There are thousands of scripts that do that
Also note that you need to remove the required if you want to do simple error handling yourself. If you want custom error handling taken care of by HTML5, you will face compatibility issues in IE <11
HTML5 form required attribute. Set custom validation message?
So this one uses simple validation now I removed required
<html>
<head>
<script>
function WriteToFile(passForm) {
var fso = new ActiveXObject("Scripting.FileSystemObject");
var fileLoc = "E:\\sample.csv";
var file = fso.openTextFile(fileLoc, 8, true, 0);
file.writeline(passForm.inputText.value + ',' +
passForm.timeSpent.value + ',' +
passForm.SystemDate.value + ',' +
passForm.UserName.value);
file.Close();
alert('File created successfully at location: ' + fileLoc);
}
function pad(num) {return String("0"+num).slice(-2)}
function systemDate() {
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth() + 1;
var yyyy = today.getFullYear();
document.getElementById("date").value = pad(mm) + '/' + pad(dd) + '/' + yyyy;
}
window.onload=function() {
systemDate();
document.getElementById("myForm").onsubmit=function() {
if (this.inputText.value=="") {
alert("Please enter Ticket Number");
this.inputText.focus();
return false;
}
if (this.timeSpent.value=="") {
alert("Please enter TimeSpent");
this.timeSpent.focus();
return false;
}
WriteToFile(this);
return false; // cancel submit
}
}
</script>
</head>
<body>
<p>Happily log your effort!</p>
<form id="myForm">
Ticket Number : <input id="inc" type="text" name="inputText" size="20"><br> Effort(In Hours): <input id="tsp" type="text" name="timeSpent" size="20"><br> Date(Effor Put On) : <input id="date" type="text" name="SystemDate"
required="true"><br> Effort Logged By: <input type="text" name="UserName" value="Abrar" disabled="true"><br>
<input type="Submit" value="submit">
</form>
</body>
</html>

Jquery :How to store textbox value clientside and display?

The below code will update the display value enter by user in textbox when button clicked but in this code it will not preserve the previous value enter by user .
<h1>Type your comment below </h1>
<input id="txt_name" type="text" value="" />
<button id="Get">Submit</button>
<div id="textDiv"></div> -
<div id="dateDiv"></div>
jQuery(function(){
$("button").click(function() {
var value = $("#txt_name").val();
$("#textDiv").text(value);
$("#dateDiv").text(new Date().toString());
});
});
Now I want preserve all the value enter by user and when user will submit the button show both value previous as well as current.
How to achieve this ?
Can below code will help to preserve all the value
var $input = $('#inputId');
$input.data('persist', $input.val() );
If yes how to display all value previous,current etc. when user click on button ?
If i got this right, this is what you need?
<h1>Type your comment below </h1>
<input id="txt_name" type="text" value="" />
<button id="Get">Submit</button>
<script type="text/javascript">
jQuery(function(){
$("button").click(function() {
var value = $("#txt_name").val();
$("#section").prepend('<div class="textDiv">'+value+'</div>')
$("#section").prepend('<div class="dateDiv">'+new Date().toString()+'</div>')
$("#txt_name").val('');
});
});
</script>
<!-- each time you press submit, a new line will be pushed here -->
<div id="section">
</div>
If you want to display only the previous and current value the user submitted and use the data function then:
$("button").click(function() {
var input = $("#txt_name").val();
var previous = $("#textDiv").data('previous') || '';
$("#textDiv").text(previous+input);
$("#textDiv").data('previous',input);
$("#dateDiv").text(new Date().toString());
});
If you want all the values and you want to store them, then I would create an array. But you could always concatenate the string.
var arr = [];
$("button").click(function() {
var input = $("#txt_name").val();
arr.push(input);
var previous = $("#textDiv").data('previous') || '';
$("#textDiv").text(previous+input);
$("#textDiv").data('previous',previous+input);
$("#dateDiv").text(new Date().toString());
});
Without using .data() you can do this:
$("button").click(function() {
var input = $("#txt_name").val();
$("#textDiv").text($("#textDiv").text()+input);
$("#dateDiv").text(new Date().toString());
});
Instead of using two separate divs for message and date, you can use a single div.
<h1>Type your comment below </h1>
<input id="txt_name" type="text" value="" />
<button id="Get">Submit</button>
<div id="msgDiv"></div>
$(document).ready(function() {
var preservedTxt = '';
$("button").click(function() {
var input = $("#txt_name").val();
var date = new Date().toString();
var msg = input + ' - ' + date;
preservedTxt = preservedTxt + '<br>' + msg;
$('#msgDiv').html(preservedTxt);
});
});
Jsfiddle : https://jsfiddle.net/nikdtu/p2pcwj2f/
Storing values in array will help
jQuery(function(){
var name=[];
var time=[];
$("button").click(function() {
var value = $("#txt_name").val();
name.push(value);
$("#textDiv").text(name);
time.push(new Date().toString())
$("#dateDiv").text(time);
});
});

How do I INSERT data from jquery textBox into MySql database using Foreach in Php, or any other way to accomplish this goal?

I need the following to happen:
A form with multiple input boxes that receives user information.
An "Add User" button that allows for additional user input.
A submit button that will INSERT the data from the form into the designated database column, and creates a new row in the database for
each new user.
I'm very new, and don't know how to loop the $_REQUEST array on the results.php page to do this. I am open to any suggestions. Thank you in advance.
var fname, lname, dob, input, inputCount = 0;
$(window).load(function() {
newUser();
})
function newUser() {
$('#box >div').hide();
inputCount++;
input = $('<div data-id="' + inputCount + '">Entry ' + inputCount + '<br><br></div>').appendTo('#box');
fname = $('<input type="text" name="fname' + inputCount + '" placeholder="First Name ' + inputCount + '"><br><br>').appendTo(input);
lname = $('<input type="text" name="lname' + inputCount + '" placeholder="Last Name ' + inputCount + '"><br><br>').appendTo(input);
dob = $('<input type="text" name="dob' + inputCount + '" placeholder="Date Of Birth ' + inputCount + '"><br><br>').appendTo(input);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<form action="results.php" method="post">
<body>
<span id="box"></span>
<button type="button" onclick="newUser()">Add User</button>
<br>
<br>
<input type="submit" value="Submit">
</body>
</form>
Your request is sent to PHP. It is mistaken to search for request parameters in $_REQUEST. You need to search them in $_POST.
You need to define a name attribute to your form fields to be passed. In your newUser javascript function add the new user's data into the form html. With jQuery, you would do something like $("#box").append(<your code>).
Your code should be something like an input, which has a name and the needed value. Then, parse the value(s) with the given name at results.php and insert the necessary values.

JavaScript function not working in Firefox and Safari (just in Chrome)

I have a page with already other JavaScripts correctly working... apart from this one:
<script>
function add(numDaysToAdd) {
var data_in = new Date (document.WADAInsertForm.data_in.value);
var data_out = data_in.setDate(data_in.getDate()+numDaysToAdd);
var final_day = data_out.getDate();
var final_month = data_out.getMonth() + 1;
var final_year = data_out.getFullYear();
document.WADAInsertForm.data_out.value = final_year+'-'+final_month+'-'+final_day;
}
</script>
This script is triggered by an OnChange call on a checkbox together with a OnClick event. To clarify:
<input type="checkbox" name="product" value="Insurance plan: 1 month" id="product" onClick="this.form.price.value='41.40'" onChange="add(+30)">
When I test the page in Chrome it does all the homeworks: insert the price value in the "price" field and update the "data_out" field with the proper value.
When I do the same in Firefox and Safari... it works only the "price" setting.
Any suggestions or help?
onChange="add(+30)"
Here +30 doesn't represent any String or any Integer in your script it would through a type error, to add days to the current date you could use this script
<script type="text/javascript" language="javascript">
function AddDays(toAdd) {
if (!toAdd || toAdd == '' || isNaN(toAdd)) return;
var d = new Date();
d.setDate(d.getDate() + parseInt(toAdd));
document.getElementById("result").innerHTML = d.getDate() + "/" + d.getMonth() + "/" + d.getFullYear();
}
</script>
---------------------- UI ---------------
<div id="result">
</div>
<input type="text" value="0" onkeyup="AddDays(this.value);" />
onClick isn't valid. Use onclick.
And I find it strange to have both onclick and onchange on a checkbox. You should include your onclick in the onchange.

using a javascript returned value and then adding it to a ruby database

I have a string that needs to be turned into a date attribute to be stored in a Ruby database.
There is a javascript function that collects the data and submits it to a ruby method which in turn submits to the database. However one of the fields is a "Date" field. Not a "DateTime" field so i cannot use the Date() function provied by js. The string i have is already in the format needed its simply getting the db to recognise this.
the html
<form action="/submiteffort" id="effort_form" method="post">
<input type="hidden" id="week_commencing" name="week_commencing" value="x">
<input type="hidden" id="task_id" name="task_id" value="x">
<input type="hidden" id="effort_hours" name="hours" value="0">
</form>
<!-- Javascript code to submit the hidden form -->
<script>
function submiteffort( elem, name )
{
var date = getdate();
$("#week_commencing").val(date);
$("#effort_hours").val( $( elem ).val() );
$("#task_id").val( name );
$("#effort_form").submit();
return true;
}
getDate() function
function getdate()
{
var myspan = document.getElementById('startDate');
var span_textnode = myspan.firstChild;
var span_text = span_textnode.data;
myDateParts = span_text.split("/");
var d = myDateParts[0];
var dd = days(d);
var m = myDateParts[1];
var subSection2 = m.substring(1,0);
if (subSection2 == "0") {
mm = m;
}
else {
mm = "0" + myDateParts[1];
}
var yy = myDateParts[2];
var actDate = yy + "-" + mm + "-" + dd;
return actDate;
}
submit method in the controller
def submit
effort = Effort.new
effort.user_id = 10 #current_user.id
effort.project_task_id = params[:task_id]
effort.week_commencing = params[:wc]
effort.hours = params[:hours]
effort.save
respond_to do |format|
format.html
format.js
end
end
How do i get my database to recognise that the value i want needs to the a "DATE" and submit it to the database?
If you're submitting a date in a format that Date recognizes, the conversion should be done for you. This requires that week_commencing is declared as a :date type column.
Have a look at your log/development.log to see what the params are set to for the request in question. Make sure that the generated date is coming through correctly.

Categories

Resources