Javascript id as parameter in href - javascript

Second image ,First image I have a set of links, which will open a pop-up form.
When the link is clicked,I want to send a parameter to the form and then use it on form submission.
I'm able to set the value to be passed as id of <a> tag. Can I send to further?
<div> <span>Chapter $i:</span>
<a href='$viewlink '>View</a><span class='status'>Status:$status </span>
<a href=$reqlink id=$i data-rel='popup' class='ui-btn ui-btn-inline ui-corner-all ui-icon-check ui-btn-icon-left'>Request Access</a></div><br/>";
<form method="post" action=" " id="myPopup" data-role="popup" style="padding:10px">
<h3>Enter your details</h3>
<input type="text" name="name" id="name" placeholder="Name" required>
<input type="email" name="email" id="email" placeholder="Email" required>
<input type="date" name="date" id="date" placeholder="Intended completion date" required>
<input type="submit" data-inline="true" value="Submit" name='submit'>
</form>
Is it possible to do in javascript? How to do it?

Option #1:
Set up hidden inputs, and send the values to them when clicking the link. You can then get these on the other end where the form is sent.
(Note: in my code examples I'm explicitly using PHP as that's where you seem to have copied your code snipped from)
echo "<a href='$viewlink' onclick='$(\'#viewlink\').val(1);'>View</a><span class='status'>Status:$status </span>
<!-- Do the following inside the form -->
<input type='hidden' name='viewlink' id='viewlink' value='0' />";
And on the PHP receiving end you can do this:
if ($_POST['viewlink'] == 1) {
// do stuff
}
Option #2:
Alternatively you could send the data to a javascript array, prevent posting on submit of the form, take care of adding the array to the form action as query string, then explicitly send the form.
echo "<a href='$viewlink' onclick='linkClicked('viewlink');'>View</a><span class='status'>Status:$status </span>
This is what you'd do in your javascript file:
var queryString = [];
function linkClicked (type) {
queryString[type] = 1;
}
$("#myPopup").submit(function(event) {
event.preventDefault();
$(this).attr('action', $(location).attr('host') + $.param(queryString));
$(this).submit();
});
And on the PHP receiving end you can do the following (note the $_POST from above has changed to $_GET):
if ($_GET['viewlink'] == 1) {
// do stuff
}

try this..
<a id = 'yourid' class = 'mybtn'>click me..</a>
<form id = 'myform'>
....
</form>
Jquery
$(document).ready(function(){
$('.mybtn').click(function(){
var id = $(this).attr('id');
var SubmitForm = $("#myform").serializeArray();
$.post("somepage.php",
{
SubmitForm:SubmitForm,
ID:id
},
function(res){
alert(res);//your result..
});
});

Related

Pre-populate HTML form text from URL

I am using this form on my php file to create the form
<input type="text" name="OrderLNumber" id="OrderLNumber" >
<br>
<input type="submit" name="submit" value="Status">
</form>
after that I am trying to pre-fill the form OrderLNumber field from this URL:
status/2727?OrderLNumber=24206927
Page loads normally but field is not filled as I intend to. How can I make this work ?
You need to get the order number from the url by using the $_GET['OrderLNumber'] variable.
The code below will test to see if the form has been submitted. If the from has loaded fresh with no POST data it will grab the order number from the url. If the form has been submitted and there is POST data it will use whatever is in the form for the order id.
Like so:
<?php
if(isset($_POST['OrderLNumber']) && $_POST['OrderLNumber']){
$orderLNumber = $_POST['OrderLNumber'];
}else{
if(isset($_GET['OrderLNumber']) && $_GET['OrderLNumber']){
$orderLNumber = $_GET['OrderLNumber'];
}
}
?>
<form action="" method="POST">
<input type="text" name="OrderLNumber" id="OrderLNumber" value=" <?php echo $orderLNumber; ?> " ><br>
<input type="submit" name="submit" value="Status">
</form>
Hope this helps.

HTML / js. Need two different forms on one page submits separately

I can't find any answer then ask:
I have to different forms on the page: the one is "ask for call" (placed on every page on the site) and the second is a simple "contact form" (placed only on contact page).
Both are validates without problems, do they are created for also good on the different page. Both has fields which are required. They has different names and IDs.
The error occurs when user on the contact page. There are two forms together. By the order contact is first. And when I use it, a mail sends.
But when I try to send call request with the second form on the page, it doesn't action because on the first form required wasn't filled or didn't match restrictions.
Why submit button from the second form takes data from the first?
Below forms in the order on the contact page and processing functions.
First form (contact)
<form id="message" name="contact_message" onsubmit="return false;" method="post">
<div class="hover">
<label for="message-name">Введите ваше имя:</label>
<input id="message-name" name="name" type="text" placeholder="Имя" title="Пожалуйста, введите ваше имя." required>
</div>
<div class="hover">
<label for="message-email">Введите ваш email адрес:</label>
<input id="message-email" name="email" type="email" placeholder="xxx#xxx.xx" title="Пожалуйста, введите корректно ваш email." required>
</div>
<div class="hover">
<label for="message-text">Введите ваше сообщение:</label>
<textarea id="message-text" name="text" placeholder="Текст сообщения" title="Пожалуйста, введите текст сообщения. Минимум 9 символов." minlength="9" required></textarea>
</div>
<input type="hidden" name="type" value="contact_page">
<button id="submit-contact" class="empty blue button medium" type="submit">Отправить</button>
<div class="c-clearfix"></div>
</form>
The second form
<form id="call-ask-form" name="call-ask-form" class="full-width" onsubmit="return false;" method="post">
<label for="phone-name">Ваше имя</label>
<input id="phone-name" type="text" name="name" placeholder="Введите ваше имя" minlength="2" required>
<label for="phone-phone">Ваш номер телефона (только цифры)</label>
<input id="phone-phone" type="text" name="phone" placeholder="+41234567890" maxlength="16" required>
<label for="phone-time">Время в формате ЧЧ:ММ, с 9 до 17 в будние дни, когда вы ожидаете звонок.</label>
<input id="phone-time" type="text" name="text" placeholder="ЧЧ:ММ" maxlength="5">
<input id="type" name="type" type="hidden" value="call_ask">
<button form="call-ask-form" id="call-submit" class="filled green medium full-width button" type="submit">Отправить запрос</button>
</form>
JS
And here the page_type variable gets data from the first form every time I push submit on the second form. And switch cases on CONTACT, but CALL REQUEST.
$(document).ready(function() {
$("#submit, #call-submit").click(function() {
var proceed = true;
var page_type = $('input[name=type]').val();
//validation
if(proceed)
{
var form;
//choosing type of a message
switch (page_type) {
case 'contact_page' :
// preparing data from CONTACT form
break;
case 'call_ask' :
// preparing data from CALL REQUEST form
break;
case 'calculator' :
break;
default :
}
// ajax post data
$.post('/assets/components/mailer2.php', post_data, function(response){
if(response.type == 'error'){ //load json data from server and output message
output = '<div class="error" style="background-color: red; color: white;">' + response.text + '</div>';
} else {
output = '<div class="success" style="background-color: green; color: white;">' + response.text + '</div>';
}
$(form).append(output).slideDown();
}, 'json');
}
});
Why this happens? Kindly asking you for help.
In the line $('input[name=type]').val();, this will always try to find the value of the first input matching the name criteria on the whole page.
But, note that both of your forms have inputs with the same name.
Javascript will not be very friendly when multiple elements have the same name. Instead, you will either need to rename them or ensure that you better reference which one you are trying to get:
The below code will get you the correct page_type: (Note that in events, this will be set to the current element which in the below case will be one of the <form /> tags which you can use to only traverse it's children using $(this).find(...) as opposed to $(...))
$('form').on('submit', function(e){
var page_type = $(this).find('input[name=type]').val();
alert(page_type);
e.preventDefault();
})

Submit Form With Both Action and Onsubmit Function

My JS is not that great so I have been fiddling with this for a while now.
I have a form which is being POST to another file when the submit button is clicked. When it is clicked I also want to show an alert then redirect the user back to a URL.
The redirecting code works just fine on a button where I call the function "onclick" like so:
<button onclick="test()">Return</button>
But I don't want to have an extra button for this...I want the form to POST then show an alert box then go to URL specified but I get not a function error from console, thanks.
<iframe name="noreloadhack" style="display:none;"></iframe>
<form action="http://www.example.com/test.php" onsubmit="return test();" method="post" target="noreloadhack">
JS:
<script>
function test() {
alert('Hello World');
var return_url = document.getElementById('return_url').value;
window.location.href= return_url;
}
</script>
If it makes a difference I have the form target set to a hidden iframe as a hack to not reload page on submit (I know, not the best method). I'm pretty much using 4 form attributes here.
I have some old code that I used to solve a similar situation. Where I wanted to submit a form but not reload the page, here it is. Since there were only 4 input fields I just grabbed the values using jquery.
Javascript:
function processForm() {
var teamMembers=new Array();
console.log($("#"));
var schoolName=$("#schoolname").val();
var teamMembers=new Array();
teamMembers.push($("#contestant1").val());
teamMembers.push($("#contestant2").val());
teamMembers.push($("#contestant3").val());
$.ajax({
method: "POST",
url: "php/register.php",
data: { schoolname: schoolName, teammembers:teamMembers.toString()}
})
.done(function( msg ) {
alert( "Your team is now registered " + msg );
$('#register').hide();
location.reload();
});
// You must return false to prevent the default form behavior
// default being reloading the page
return false;
}
HTML:
<form id="registration_form" onsubmit="return processForm()" method="POST">
<p style="margin:0px;">School Name:</p>
<input type="text" id="schoolname" name="schoolname" autocomplete="off" class="input" required>
<hr>
<p style="margin:0px;">Contestants</p>
<div id="teammembers">
<input type="text" id="contestant1" name="contestant1" autocomplete="off" class="input" required>
<p></p>
<input type="text" id="contestant2" name="contestant2" autocomplete="off" class="input" required>
<p></p>
<input type="text" id="contestant3" name="contestant3" autocomplete="off" class="input" required>
</div>
<input type="submit" id="registered">

Javascript Output results with input data

I am a newbie to javascript, I am making a simple script which will show appended link with the data entered in input field, Basically it should get the data from input field and generate link with data being submitted in input field.
Similar to the example below
Input: tony#mail.com ...> after clicking Send button
processing....
Output link: www.domain.com/route.php?email=tony#mail.com
I found this code similar to mine but it wont works like i am looking for.
<p>Enter your email or User ID
<input type="text" name="foo" id="foosite" value="" />
<a href="#"
onclick="this.href = ('http://' + document.getElementById('foosite').value + 'www.domain.com/route.php?email=')"
target="_blank">send</a>
Is that possible in javascript to make a script like this which will generate output without reloading the page?
You have the getelement in the wrong place. It should be like this if you want to do it that way.
<input type="text" name="foo" id="foosite1" value="" />
send
<input type="text" name="foo" id="foosite2" value="" />
send
http://jsfiddle.net/bowenac/J2Mc5/3/
Split your JS logic from your HTML
HTML
<p>Enter your email or User ID
<input type="text" name="foo" id="foosite" value="" />
</p>
send
<div id="url_value"></div>
JS
var a = document.getElementById('link')
a.onclick = function(e){
e.preventDefault();
var value = document.getElementById('foosite').value;
var route = "http://www.domain.com/route.php?email=" + value + ', ';
var data = "http://www.domain.com/data.php?email=" + value + ', ';
var form = "http://www.domain.com/form.php?email=" + value;
document.getElementById('url_value').innerHTML = route + data + form
}
DEMO
You can add form to your html code and send data to server using form submit, in this case you can change the action of the form before submit to custom link.
<form name="form1" action="" onSubmit="onsubmit(this)">
<p>
Enter your email or User ID
<input type="text" name="foo" id="foosite" value="" />
<input type="submit" value="send" />
</p>
</form>
<script>
function onsubmit(form)
{
//change the action of the form to your link.
form.submit();
}
</script>

How can I send a variable to a form using this javascript function?

I've got this onclick call:
onClick="mySubmit();
which calls this function:
function mySubmit(){
document.getElementById("myForm").submit();
}
which then submits this form:
<form id="myForm" action="action.php" method="post">
My question is: how do I send a variable to the form from the onClick to get something like <form id="myForm" action="action.php?id=**(the variable sent from the onclick goes here)**" method="post">
Thanks!
Easiest way: append a hidden field to the form.
<form id="myForm" action="action.php" method="post">
<input type='hidden' id= 'hiddenField' name='id' value='' />
<script>
function mySubmit() {
document.getElementById('hiddenField').value = "Whatever I want here";
document.getElementById("myForm").submit();
}
</script>
Or use a function like
function addHiddenField(form, props) {
Object.keys(props).forEach(fieldName => {
var field = form[fieldName];
if (!field) {
field = document.createElement('input');
field.type = 'hidden';
field.name = fieldName;
form.appendChild(field);
}
field.value = props[fieldName];
});
}
document.querySelector('form').addEventListener('submit', () => {
addHiddenField(this, {
someQueryName: 'someQueryValue',
otherQueryName: 'otherVal'
});
});
<form>
Name
<input name=name />
<input type=submit />
</form>
Note that you can use DevTools to modify the iframe's sandbox to allow it to submit forms and you can verify the posted URL. sandbox="... allow-forms"
place a input type hidden inside the form then submit the form
<input id="id" name="id" type="hidden" />
set the value of the hidden field in your javascript submit()
document.getElementById('id').value = **;
but by setting form method="post" the id will not be the part of query string, i.e. the url will remain action.php
instead
if you really want the id in query string i.e. url action.php?id=** then you need to change the form method="get", by this the hidden field id will automatically be the part of the url i.e action.php?id=**
read about difference between get and post
here is how you access posted value on next page if you really need to use method="post" action="action.php"
Your HTML :
<form id="myForm" action="#" method="post">
<input type='hidden' id="id" name='id' value='123' />
<input type='submit' name='submit' value='Click me !' onclick='addParam()' />
</form>
Your Script :
function addParam() {
var url = "action.php?id=" + document.getElementById('id').value;
document.getElementById("myForm").setAttribute('action', url);
}
Thank You.

Categories