So I've got myself a form here shown below; I'm trying to change the form's action link based on the selection. However it's not really working for me.
<form action="">
<select id="location">
<option value="http://www.google.com/php:id=384733">New York</option>
<option value="http://www.google.com/php:id=384734">Georgia</option>
</select>
<input type="submit" value="Submit">
</form>
$("#location").change(function() {
var action = $(this).val();
$("form").attr("action")};
});
)};
There's more then just the two states, I'll have all states but for this example I've listed two. the value would be the url with different ID numbers as shown above.
In the end, if I selected New York the action in the form code would get updated and show something similar to this;
<form action="http://www.google.com/php:id=384733">
You're almost there, just a few syntax errors, and you're never setting the attribute
$("#location").on('change', function() {
$(this.form).attr("action", this.value);
});
There seems you have a typo in your javascript, check this:
$("#location").change(function() {
var action = $(this).val();
$("form").attr("action",action);
});
Related
I'm working on a collection of web apps using REACT JS. For part of the current app I'm working on, I have a modal that renders on a state change and has a form to receive a name with some related data. I want the submit button in this form to submit the code to a submitNewName() function which will compare the submitted name & data to names & data from a JSON file. Unfortunately, I cannot test to see if any of my code works because the page refreshes upon submission, which refreshes the developer console.
Within my submitNewName() function, I have the following line of code:
var newName = document.getElementById("newNameForm").submit(). I read another similar question where someone suggested adding function(e) {e.preventDefault();} as an argument for .submit, but when I tried that it didn't change anything.
Here's my form:
<form id="addNameForm" className="RNGpopupTXT">
Name: <input type="text" name="name"/>
<br/><br/>
Type: <select>
<option value="fname">First Name</option>
<option value="lname">Last Name</option>
<option value="sname">Single Name (e.g. Madonna)</option>
<option value="title">Title</option>
</select>
<br/><br/>
Gender: <select>
<option value="mg">Male</option>
<option value="fg">Female</option>
<option value="ng">Non-specific</option>
</select>
<br/><br/>
Tags: <input type="text" size="40" name="tags" placeholder=" eg. 'Star Wars,Scifi,Space'"/>
<br/><br/><br/><br/>
<div align="center">
<input type="submit" value="Submit" className="mdc-button" style={{ textDecoration: 'none' }} onClick={() => this.submitNewName()}/>
</div>
</form>
and here's my function:
submitNewName() {
var newName = document.getElementById("newNameForm").submit(function(e) {
e.preventDefault();
});
}
I would like the data from the form to be given to the function in a way that would allow it to be compared to the JSON file data. I also do not want the page to refresh, as that refreshes the state of the page, closing the modal prematurely. When I run the program now, it does send an error message to the console, but I cannot read what it says because the console is refreshed with the web page.
It feels like you could use more React to make your life easier here.
You don't have to use the form's onSubmit event. You could just add an onClick handler to the button. In that function, you could do all the comparing you want and, whrn you're ready, it can do the submitting logic too.
If you wanted to compare the form's values, you might want to keep those values in state. To do so though, you would need onChange functions on each of the form elements to update the state as the user provides input.
As I didn't see much React code in your example, I took the liberty of writing some out. Hopefully it will help you:
https://codesandbox.io/s/elastic-shape-yrv0b
that might be a simple question, but I am not yet so firm with JavaScript.
I want to have a search form with autocomplete using select2.
When the user selects a result in the select2 dropdown box, I want to submit the search form right away so that I do not need a button for the form.
I found the select2:select event handler - but I do not get it to work. Any help?
My select2 works fine and if I include a button, I can submit the form and receive the selected object id:
<form action="" method="get" id="project-search">
<select class="form-control"
data-autocomplete-light-function="select2"
data-autocomplete-light-url="/output/project-autocomplete/"
data-placeholder="Suche nach Projektnr. oder Projektleiter"
id="id_projekt" name="projekt">
<option value="" selected="selected">----------</option>
</select>
</form>
That javascript snippet does not seem to work:
<script type="text/javascript">
$(document).ready(function() {
$eventSelect.on("select2:select", function() {
console.log("select2:select");
$(this).parents('form').submit();
});
});
</script>
Edit: I get this error message in my chrome console:
Uncaught ReferenceError: $eventSelect is not defined
Thank you!
I am using django with django-autocomplete-light for the backend btw.
https://api.jquery.com/change/
Jquery has a function able to detect changes on select/checkboxes. Try:
$('#id_projekt').change(function(){
$('#project-search').submit();
});
A simple vanilla solution
<select onchange="this.form.submit()">
...
</select>
I am trying to validate Bootstrap multiselect dropdown using the code given below, the form is getting validated but i did'nt get the proper output, the
validation message is above the selectbox and the message gets multiplied when
clicking on the submit button and after selecting option the message did'nt gets removed. Please help to solve my problem.
<script type="text/javascript">
$(document).ready(function() {
$.validator.addMethod("needsSelection", function (value, element) {
var count = $(element).find('option:selected').length;
return count > 0;
});
$.validator.messages.needsSelection = 'Select Atleast One College';
$("#User").validate({
rules: {
'college[]': {
needsSelection: true
}
},
}
});
$("#submit").click(function(e) {
var isvalidate=$("#User").valid();
if(isvalidate=="true")
{
}
else
{
$("#User").submit();
}
});
});
<form id="User" name="User" method="post" enctype="multipart/form-data" action="index">
<select data-placeholder="Choose College Name" name="college[]" class="chosen-select" id="college" multiple tabindex="4">
<option value=""></option>
<option value="1">abc</option>
<option value="2">abc1</option>
</select>
<a id="submit">Submit</a>
</form>
This is not a direct answer to your question, but may provide a solution to your problem.
First, change the anchor tag to a button -- because anchor tags have built-in navigation behaviour that you must counter (event.preventDefault()) and therefore add needless complexity. How about a button (input or button tags) or a div tag, or a p?)
Next, a simpler structure to evaluating your form:
jsFiddle Demo
HTML: (just changed your anchor submit button to:
<input id="dosubmit" type="submit" value="Submit" />
Note: do not use "submit" as the id for a submit button, as that is a reserved keyword
javascript/jQuery:
$('#User').submit(function(e){
var col = $('#college').val();
if ( col==null || col=='' || col=='Please choose one:' ){
$('#college').css('background','yellow').focus();
return false;
}else{
$('#college').css('background','transparent');
alert('Form submitted');
//continue to submit the form - but not now
return false;
}
});
Please consider this verification script for your project.
This is not an answer to your question but I will advise you and encourage you to use a server-side validation together.
Your data should be validate and as needed sanitzed on the php file that receives the ajax call.
If something is going wrong there, the response will always be passed back to your form giving your users the needed feedback.
You can find many examples on the internet of how to do this.
See here an example: https://scotch.io/tutorials/submitting-ajax-forms-with-jquery
So to recap: Dont't do client-side validation!!
I have a list pulled from a database that currently uses 2 submit buttons. one to refresh the page with a different set of data and the other to update the page.
the code is basically...
// this is a little bit pseudo so dont worry about spelling mistakes...
<?php
if($_POST['update']) {
// update database
}
if($_POST['filter']) {
// show different data
}
?>
<form type="post">
<button type="submit" name= "update" value="update">Update</button>
<select name="selectitem">
<option value="1">1</option>
<option value="2">2</option>
</select>
<button type='submit' name='filter' value='filter'>Filter</button>
</form>
This works fine but I was thinking it would be better to have the select element do the refresh when changed using onChange but how do i get it to submit the right button (in this case the filter button). I am using jquery so suggestions using that would be fine too.
the form posts back to the same page so it can refresh or update the data based on the select element.
I guess i want to get rid of the filter button but perform its specific action onchange of the select element.
hope you can help
thanks
Set an event handler on the select element that will trigger a click to the button.
Like this:
$('select[name="selectitem"]').change(function(e) {
$('button[name="filter"]').click();
});
I hope that helps!
Making Html Form Input field to remain unchange on submission.
When i submit the form, the form inputs for ball and comments gets reset to empty.
Now what i want is when i submit the form, the values in the inputs select field for ball remains unreset while comments fields values will reset
as usual. any help below is the working code
$('body').on("click",".addComment",function(){
var element = $(this);
var id = element.attr("id");
$('#commentBox'+id).slideToggle(200);
$('#comment'+id).focus();
$('#comment'+id).val('');
$('#comment'+id).attr("placeholder", "Write a message..");
});
$('body').on("click",".comBtn",function(){
var element = $(this);
var cid = element.attr("id");
var ball=$('#ball').val();
var comment=$('#comment').val();
var datasend = 'com='+ comment + '&pid=' + cid +'&ball='+ball;
if(comment==""){
$('#comment'+cid).focus();
$('#comment'+cid).attr("placeholder", "Enter the comment..");
}else{
$.ajax({
type:"POST",
url:"comment.php",
data:datasend,
cache:false,
success:function(html){
$('#loadcomment'+cid).append(html);
$('#comment').val('');
$('#ball').val('');
}
});
}
return false;
});
<form action="" method="post">
<select name="ball" id="ball">
<option>none</option>
<option value="left">left</option>
<option value="right">right</option>
</select>
<input name="comment" id="comment" type="text">
<input id="comBtn" type="submit"/>
</form>
I am simply moving this to an answer because I put it in as a comment thinking there might be more ...
On the success of your $.ajax call, remove the $('#ball').val('') line so that it doesn't change.
Basically, the val statement has two purposes.
As .val("123"): this will change the value of the element to 123, an assignment.
As .val(): this will obtain the value from the element without changing it.
As you wrote it, the $('#ball').val('') code resets ball's value to an empty string.
The short answer to this will be:
You can resetting the select dropdown using $('#ball').val(0);
I can see few issues in the code, first of all you need to wrap the entire block with
$(function() {
// your code goes here
});
Second thing take advantage of HTML5 by adding the necessary attributes like required="required" and placholder on your inputs and adding novalidate on the form like the following:
<form method="post" novalidate>
<input type="text"
required="required"
placeholder="Your placeholder goes here"/>
Use e.preventDefault(); to prevent the form from being submitted cause you are posting using ajax.and use only submit event
$('form').on("submit", function(e) {
e.preventDefault();
// your other functions
});
Put the action on the form attribute instead of the js variable, html is cheaper to manage.
<form action="comment.php">
Then in the js
url: $('form').attr('action'),
Of course better save it in a variable then pass it but this is just an example
Use $('form').serialize(); instead of constructing the data your self
`data:datasend, // bad
`data: $('form').serialize() // good
Form serialize jquery api