Setting value with Javascript - php

I have this code:
<html>
<head>
<script type="text/javascript">
/***********************************************
* Drop Down Date select script- by JavaScriptKit.com
* This notice MUST stay intact for use
* Visit JavaScript Kit at http://www.javascriptkit.com/ for this script and more
***********************************************/
var monthtext=['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sept','Oct','Nov','Dec'];
function populatedropdown(dayfield, monthfield, yearfield){
var today=new Date()
var dayfield=document.getElementById(dayfield)
var monthfield=document.getElementById(monthfield)
var yearfield=document.getElementById(yearfield)
for (var i=0; i<31; i++)
dayfield.options[i]=new Option(i, i+1)
dayfield.options[today.getDate()]=new Option(today.getDate(), today.getDate(), true, true) //select today's day
for (var m=0; m<12; m++)
monthfield.options[m]=new Option(monthtext[m], monthtext[m])
monthfield.options[today.getMonth()]=new Option(monthtext[today.getMonth()], monthtext[today.getMonth()], true, true) //select today's month
var thisyear=1920; // fixed start year of 1900
var nowyear = 1994;
var diff = nowyear - thisyear +1; // number of years from 1900
for (var y=0; y<diff; y++){
yearfield.options[y]=new Option(thisyear, thisyear)
thisyear+=1
}
}
</script>
<script>
function getcombined(){
var year = document.getElementbyId("yeardropdown").value;
var month = document.getElementById("monthdropdown").value;
var day = document.getElementById("daydropdown").value;
var combineddob = year + "-" + "month" + "-" + day;
document.getElementById("hidden1").value=combineddob
}
</script>
</head>
<body>
<form action="" name="someform">
<select id="daydropdown" name='day' value="daydropdown">
</select>
<select id="monthdropdown" name='month' value="monthdropdown">
</select>
<select id="yeardropdown" name='year' value="yeardropdown">
</select>
<input type='hidden' id='hidden1' name='dob' value="" />
<input type='submit' />
</form>
<script type="text/javascript">
window.onload=function(){
populatedropdown("daydropdown", "monthdropdown", "yeardropdown")
}
</script>
</body>
</html>
I need the <input type='hidden' id='hidden1' name='dob' value='' /> to update to var combineddob when the form is submitted.
I have tried several methods, but I do not know much about javascript so I am not good with these kinds of fixes.
I may be over looking something, but I have not yet figured out what is wrong here.

If you want something to happen before a user submits the form, you should set the onsubmit property of the form. In this case:
<script>
<!--
function getcombined(){
var year = document.getElementById("yeardropdown").value;
var month = document.getElementById("monthdropdown").value;
var day = document.getElementById("daydropdown").value;
var combineddob = year + "-" + month + "-" + day;
document.getElementById("hidden1").value=combineddob;
return true;
}
-->
</script>
</head>
<body>
<form action="" name="someform" onsubmit='return getcombined();'>
I've added "return true" to the function to indicate that the form should actually submit afterwards. Also I fixed two typos, namely a lower case b in getElementbyId and a missing semicolon.

change your html
<input type='submit' />
to this
<input type='submit' id="submitButton" />
and in your script
window.onload = function(){
populatedropdown("daydropdown", "monthdropdown", "yeardropdown");
var submitBtn = document.getElementById("submitButton");
submitBtn.onsubmit = function(){getcombined();};
};
This will allow you to run the function in onsubmit when the submit button is clicked. It will in turn call the function getcombined(); and then submit the form.
EDIT
Perhaps you should change these two lines:
var combineddob = year + "-" + "month" + "-" + day;
document.getElementById("hidden1").value=combineddob
to
var combineddob = year + "-" + month + "-" + day;
document.getElementById("hidden1").value=combineddob;
and
var year = document.getElementbyId("yeardropdown").value;
to (note that getElementbyId is not a function)
var year = document.getElementById("yeardropdown").value;

First of all:
var year = document.getElementbyId("yeardropdown").value;
to:
var year = document.getElementById("yeardropdown").value;
Add onclick in submit button:
<input type='submit' onclick="getcombined();alert(hidden1.value);" />

Related

Is there a method to post form without refreshing page and after a time interval?

I am using this ajax script to keep all the information on page even after pressing submit
<!DOCTYPE html>
<html>
<head>
<title>AJAX POST Submit</title>
<script>
function ajaxpost () {
// (A) GET FORM DATA
var form = document.getElementById("myForm");
var data = new FormData(form);
// (B) AJAX
var xhr = new XMLHttpRequest();
xhr.open("POST", "0-dummy.php");
// What to do when server responds
xhr.onload = function () { console.log(this.response); };
xhr.send(data);
// (C) PREVENT HTML FORM SUBMIT
return false;
}
</script>
</head>
<body>
<form id="myForm" onsubmit="return ajaxpost()">
Name: <input type="text" name="name" required/>
Email: <input type="text" name="email" required/>
<input type="submit" id = "hello"value="Go!"/>
</form>
</body>
I essentially want to update the form and post it to "dummy.php" after few mins without having to press submit button and erasing data on page.
<script>
//var div = document.getElementById('myForm');
//var submitted = document.getElementById('hello');
function CountDown(duration, display) {
var timer = duration, minutes, seconds;
var interVal= setInterval(function () {
minutes = parseInt(timer / 60, 10);
seconds = parseInt(timer % 60, 10);
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.innerHTML ="<b>" + minutes + "m : " + seconds + "s" + "</b>";
if (timer > 0) {
--timer;
}else{
clearInterval(interVal)
document.getElementById('myForm').submit();
}
},1000);
}
function SubmitFunction(){
//submitted.innerHTML="Time is up!";
document.getElementById('myForm').submit();
}
//CountDown(5,div);
</script>
</html>
The reason I want it this way is because I am trying to make a html page which uses php to post the value of checkbox every few minutes to a text file. The value of the checkbox determines the circuit which is connected to a device which collects all the data from the text file.
so what you need is just avoid most what you wrote and just stick to the following:
<input type="button" onclick="setInterval(ajaxpost,1000);" id = "hello"value="Go!"/>
the trick here at first change the type from submit to button.
What will happen after the first click on Go, it will keep sending every second, and delete onsubmit="return ajaxpost()"
the following is the test I made:
<!DOCTYPE html>
<html>
<head>
<title>AJAX POST Submit</title>
<script>
function ajaxpost () {
// (A) GET FORM DATA
var form = document.getElementById("myForm");
var data = new FormData(form);
// (B) AJAX
var xhr = new XMLHttpRequest();
xhr.open("POST", "help.php");
// What to do when server responds
xhr.onload = function () { console.log(this.response); };
xhr.send(data);
}
</script>
</head>
<body>
<form id="myForm" >
Name: <input type="text" name="name" required/>
Email: <input type="text" name="email" required/>
<input type="button" onclick="setInterval(ajaxpost,1000);" id = "hello"value="Go!"/>
</form>
</body>
and my hello.php was just:
<?php
echo $_POST["name"]."". $_POST["email"];
Hope that answers the question.

Disabled a button based on credit date expiry date validation in jquery

I have fields of credit card expiry date.Below code user enter a month and year
<input class="expiry-month exp" name="card_exp_month" id="card_exp_month" required>
<input class="expiry-year exp" name="card_exp_year" id="card_exp_year" required>
I am getting current month and year from php date() function.
<?php
$month= date('n');
$year= date('y');
?>
<input type="text" name="curr_month" id="curr_month" value="<?php echo $month;?>"/>
<input type="text" name="curr_year" id="curr_year" value="<?php echo $year;?>"/>
This button will be disabled when user enter a expiry month or year less to current month or year
<input type='button' class='btn btn-next btn-fill btn-rose btn-wd' name='next' value='Next' id="billing_nxtBtn" />
and jquery code
$( ".exp" ).keyup(function() {
var exp_month = $("#card_exp_month").val();
var exp_year = $("#card_exp_year").val();
var curr_month = $("#curr_month").val();
var curr_year = $("#curr_year").val();
if(exp_month < curr_month || exp_year < curr_year){
$("#billing_nxtBtn").attr("disabled",true);
}else if(exp_month > curr_month || exp_year > curr_year) {
$("#billing_nxtBtn").attr("disabled",false);
}
});
I want that when user enter a expire month or year less then to current month or year then button will be disabled and when user enter a expire month or year greater then to current month or year then button will be enabled.
Issue is that button is not disbaled when user enter a expire month or year less then to current month or year
There's a couple of issues. One is because you're not removing the disabled attribute; you need to use removeAttr(). Your logic is also flawed, as if I selected 01/2019 then the button would be disabled as the month is less than the current month - you're not taking in to account years.
There is also a couple of logical improvements you can make, such as using input instead of keyup (in case people copy+paste values, or use other entry methods for accessibility) and use prop() instead of attr(). That way you can simply provide the boolean condition as the argument.
Also just FYI, this is not secure in the slightest; it's ridiculously easy to break. You should provide this client side validation as a courtesy to users only and do the business critical date check on the server side.
With all that said, try this:
$(".exp").on('input', function() {
var exp_month = $("#card_exp_month").val();
var exp_year = $("#card_exp_year").val();
var curr_month = $("#curr_month").val() || 0;
var curr_year = $("#curr_year").val() || 0;
$("#billing_nxtBtn").prop('disabled', exp_year < curr_year || (exp_year == curr_year && exp_month < curr_month));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input class="expiry-month exp" name="card_exp_month" id="card_exp_month" required>
<input class="expiry-year exp" name="card_exp_year" id="card_exp_year" required><br />
<input type="text" name="curr_month" id="curr_month" value="6" />
<input type="text" name="curr_year" id="curr_year" value="18" />
<input type='button' class='btn btn-next btn-fill btn-rose btn-wd' name='next' value='Next' id="billing_nxtBtn" disabled/>
You should place your jquery constant value with PHP constant date, not get it from input field (which is dynamic value by user input), example code as below:
$( ".exp" ).keyup(function() {
var exp_month = $("#card_exp_month").val();
var exp_year = $("#card_exp_year").val();
var curr_month = parseInt('<?= date("n");?>');
var curr_year = parseInt('<?= date("Y");?>');
if (exp_year < curr_year) {
$("#billing_nxtBtn").attr("disabled", true);
} else if (exp_year > curr_year) {
$("#billing_nxtBtn").removeAttr("disabled");
} else {
if (exp_month >= curr_month) {
$("#billing_nxtBtn").removeAttr("disabled");
} else {
$("#billing_nxtBtn").attr("disabled", true);
}
}
});
Have u try to use Jquery.change Method
$("#card_exp_month,#card_exp_year").change(function(){
var exp_month = $("#card_exp_month").val();
var exp_year = $("#card_exp_year").val();
var curr_month = $("#curr_month").val();
var curr_year = $("#curr_year").val();
if(exp_month < curr_month || exp_year < curr_year){
$("#billing_nxtBtn").attr("disabled",true);
}else if(exp_month > curr_month || exp_year > curr_year) {
$("#billing_nxtBtn").attr("disabled",false);
}
});

posting array of text fields using jquery and ajax

i dont want to use serialize() function please help me with this. I am a beginner
html
<input type='button' value='Add Tier Flavor' id='Add'>
<input type='button' value='Remove Tier Flavor' id='Remove'>
<div id='batch'>
<div id="BatchDiv1">
<h4>Batch #1 :</h4>
<label>Flavor<input class="textbox" type='text' id="fl1" name="fl[]" value=""/></label></br>
<label>Filling<input class="textbox" type='text' id="fi1" name="fi[]" value="" /></label></br>
<label>Frosting<input class="textbox" type='text' id="fr1" name="fr[]" value=""/></label></br>
</div>
</div>
<br>
</div>
this is a dynamically added fields using javascript the code is:
javascript
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var counter = 2;
$("#Add").click(function () {
if(counter>5){
alert("Only 5 Tiers allow");
return false;
}
var newBatchBoxDiv = $(document.createElement('div')).attr("id", 'BatchDiv' + counter);
newBatchBoxDiv.html('<h4>Batch #'+ counter + ' : </h4>' +
'<label> Flavor<input type="text" name="fl[]" id="fl' + counter + '" value=""></label><br>'+
'<label> Filling<input type="text" name="fi[]" id="fi' + counter + '" value=""></label><br>'+
'<label> Frosting<input type="text" name="fr[]" id="fr' + counter + '" value=""></label><br>' );
newBatchBoxDiv.appendTo("#batch");
counter++;
});
$("#Remove").click(function () {
if(counter==1){
alert("No more tier to remove");
return false;
}
counter--;
$("#BatchDiv" + counter).remove();
});
});
</script>
i am trying to post the values in an array to post it onto next .php page
i am using this
var user_cupfl = $('input[name^="fl"]').serialize();
var user_cupfi = $('input[name^="fi"]').serialize();
var user_cupfr = $('input[name^="fr"]').serialize();
serialize is not passing the values. :(
on second page i am trying to mail it using
$message .= "<tr><td><strong>Cake Flavors(according to batches):</strong> </td><td><pre>" .implode("\n", $user_cupfl). "</pre></td></tr>";
$message .= "<tr><td><strong>Filling type (Inside the cake):</strong> </td><td><pre>" .implode("\n", $user_cupfi). "</pre></td></tr>";
$message .= "<tr><td><strong>Frosting type (top of the cake):</strong> </td><td><pre>" .implode("\n", $user_cupfr). "</pre></td></tr>";
i m posting array like this
$user_cupfl=filter_var($_POST["userCupfl"], FILTER_SANITIZE_STRING);
$user_cupfi=filter_var($_POST["userCupfi"], FILTER_SANITIZE_STRING);
$user_cupfr=filter_var($_POST["userCupfr"], FILTER_SANITIZE_STRING);
your replies will be highly appreciated
Just because you name a variable user_* doesn't mean that is what the name of the field is in the serialized POST data. You would still be looking for $_POST['fl'], $_POST['fi'] etc.
I don't understand why you think you need to serialize sets of input groups individually. You should just serialize the whole form at once.
I also see no reason why you need to have all this logic around unique id's with the counter and what not. If you are not using id's at all, just drop them altogether.
You might also consider simply using clone techniques to generate your dynamically added fields. You could greatly simplify all that javascript code by doing these things.
A more reasonable implementation may look like this.
HTML (cleaning up your code - consistent use of double quotes around properties, better strategy for class and id usage, etc.)
<div id="batch">
<div class="batchDiv">
<h4 class="batchLabel">Batch #1 :</h4>
<label>Flavor</label>
<input class="textbox" type="text" name="fl[]" value=""/>
</br>
<label>Filling</label>
<input class="textbox" type="text" name="fi[]" value="" />
</br>
<label>Frosting</label>
<input class="textbox" type="text" name="fr[]" value=""/>
</br>
</div>
</div>
Javascript:
$(document).ready(function() {
$('#Add').click(function(){
var $existingBatches = $('.batchDiv');
var count = $existingBatches.size();
if (count < 5) {
// get last batch div
var $newBatch = $existingBatches.last().clone();
// reset input values to empty string
$newBatch.find('input').val('');
// change batch label
count++;
$newBatch.find('.batchLabel').html('Batch #' + count + ' :');
// append to document
$newBatch.appendTo('#batch');
} else {
// alert or whatever
}
});
$('#Remove').click(function(){
var $existingBatches = $('.batchDiv');
var count = $existingBatches.size();
// delete last batch item if more than 1 exists
if(count > 1) {
$existingBatches.last().remove();
} else {
// alert or whatever
}
});
});
Now you haven't shown your AJAX code, but all you would need to do is something like:
var url = '/some/url';
var postData = $('[some form selector]').serialize();
var dataType = '...'; //whatever dataType you are expecting back
$.post(url, postData, function(){
// success handler
}, dataType));
Your data when then be available in PHP script at $_POST['fl'], etc.

PHP How to add Textbox Without Losing Data

I use a css style for personal information cards.
For example:
<strong>Name: </strong><p>Bla Bla</p>
<h1>Contact Info</h1>
<p>E-mail: blablabla</p>
Now I want to do this with PHP. I've designed my code and template for this. When you fill two textboxes (name, e-mail) and click the button, it gives me the HTML code.
But some people has more than one e-mail. So I've to add second (3rd, 4th) textbox for them. How can I do this without losing the old textbox datas?
Name: filled
E-mail: filled
I need to enter another e-mail so lets click this button for another textbox.
Boom
Name: empty
E-mail: empty
Email2: empty
How to prevent that?
I believe it would be beneficial for everybody if you could post snippet of the code you attempted.
Anyway I have to admit I don't really understand what exactly you're trying to achieve but you may want to check out the variable passing in php PHP variable passing
If I understodd.
To do this has two ways:
1) do in Jquery.
<html>
<head>
<title>jQuery add / remove textbox example</title>
<script type="text/javascript" src="jquery-1.3.2.min.js"></script>
<style type="text/css">
div{
padding:8px;
}
</style>
</head>
<body>
<h1>jQuery add / remove textbox example</h1>
<script type="text/javascript">
$(document).ready(function(){
var counter = 2;
$("#addButton").click(function () {
if(counter>10){
alert("Only 10 textboxes allow");
return false;
}
var newTextBoxDiv = $(document.createElement('div'))
.attr("id", 'TextBoxDiv' + counter);
newTextBoxDiv.after().html('<label>Textbox #'+ counter + ' : </label>' +
'<input type="text" name="textbox' + counter +
'" id="textbox' + counter + '" value="" >');
newTextBoxDiv.appendTo("#TextBoxesGroup");
counter++;
});
$("#removeButton").click(function () {
if(counter==1){
alert("No more textbox to remove");
return false;
}
counter--;
$("#TextBoxDiv" + counter).remove();
});
$("#getButtonValue").click(function () {
var msg = '';
for(i=1; i<counter; i++){
msg += "\n Textbox #" + i + " : " + $('#textbox' + i).val();
}
alert(msg);
});
});
</script>
</head><body>
<div id='TextBoxesGroup'>
<div id="TextBoxDiv1">
<label>Textbox #1 : </label><input type='textbox' id='textbox1' >
</div>
</div>
<input type='button' value='Add Button' id='addButton'>
<input type='button' value='Remove Button' id='removeButton'>
<input type='button' value='Get TextBox Value' id='getButtonValue'>
</body>
</html>
2) in PHP using Session
Store variable in a Session after you submit your form

Adding a "REMOVE" link beside a textbox result by an array

[+] //each time I click this button the textbox will generate and I want to have a link beside each textbox, link is "remove" when I click "REMOVE" the textbox will remove..
[hello1] Remove
[hello2] Remove
[hello3] Remove
<HTML>
<HEAD>
<SCRIPT LANGUAGE="JavaScript">
var i=0,j=0;
var t1= new Array();
function createtext(){
i++;
t1[i]=document.createElement('input');
t1[i].type='text';
t1[i].name='text'+i;
t1[i].value = "hello"+i;
t1[i].size = 10;
document.forms[0].appendChild(t1[i]);
var mybr=document.createElement("br");
document.forms[0].appendChild(mybr);
}
</SCRIPT>
</HEAD>
<BODY >
<form action="" method="get" name="f1">
<input name="b1" type="button" onClick="createtext()" value="+">
<input name="b1" type="Submit"><br>
</form>
</BODY>
</HTML>
Well this is simple.
Just add a id attribute with your text field array that will be assigned to each newly created textarea like this:
t1[i].id='some_unique_suffix'+i
t1[i].onClick='remove("some_unique_suffix"'+i+')'
Then you can go on creating a remove link after each textfield via your loop and pass the id of that particular textfield to a remove function that will be called upon clicking on the remove link like this:
function remove(id)
{
$('#some_unique_suffix'+id).remove();
}
Hope you get the idea.
You can add a remove button along with the input tag like this:
var i=0,j=0;
var t1= [];
function add(){
i++;
var parent = document.forms[0];
var div = document.createElement('div');
var input = document.createElement('input');
input.type='text';
input.name='text'+i;
input.value = "hello"+i;
input.size = 10;
t1.push(input);
div.appendChild(input);
var removeButton = document.createElement("button");
removeButton.innerHTML = "Remove";
removeButton.onclick = function(e) {
this.parentNode.parentNode.removeChild(this.parentNode);
return(false);
};
div.appendChild(removeButton);
parent.appendChild(div);
}
Working demo: http://jsfiddle.net/jfriend00/ky9nv/
This code makes it easier to remove an input element and it's associated button by enclosing them in a containing div. A clicked button can then just get it's parent container and remove that.
And, since your question is tagged with jQuery (thought it doesn't save you a lot here), here's a version that uses jQuery:
var i=0,j=0;
var t1= [];
function add(){
i++;
var div = $('<div>');
var input = $('<input>')
.attr({
size: '10',
type: 'text',
name: 'text' + i,
value: 'hello' + i
}).appendTo(div).get(0);
t1.push(input);
$('<button>Remove</button>')
.click(function() {
$(this).parent().remove();
}).appendTo(div);
$("#myForm").append(div);
}
add();
add();
$("#add").click(add);
Working example: http://jsfiddle.net/jfriend00/nbXak/
<script type="text/javascript">
var i=0;
function createtext() {
i++;
$('<div id="field'+i+'">​<input type="text" name="text'+i+'" value="Hello'+i+'" size="10" /> Remove</div>').appendTo('#inputsPlaceholder');
}
function removeField (id) {
$('#'+id).remove();
}
</script>
HTML:
<form action="" method="get" name="f1" id="f1">
<input name="b1" type="button" onclick="createtext();" value="+" />
<div id="inputsPlaceholder"></div>
<input name="b1" type="submit" />
</form>
Try it: http://jsfiddle.net/Z3L5C/

Categories