I am using the validate plugin in order to send some ajax. I am having the problem that I cannot serialise select option and checkbox.
My end result is to have a string looking like dashName=aaa&dashSurname=bbb&dashArea=Blue...
With the code below I can just get the input text values; How can I validate and get the values from other elements?
here the fiddle
$('#updateMemberForm').validate();
$(document).on('click', '#saveMemberBtn', function() {
if ($('#updateMemberForm').valid()) {
var serialize = $("#updateMemberForm").serialize();
$("#test").text(serialize);
console.log(serialize);
}
return false;
});
HTML:
<form method="post" id="updateMemberForm">
<input class="" type="text" name="dashName" placeholder="Name" />
<input class="" type="text" name="dashSurname" placeholder="Surname" />
<br>
<select onchange="" name="dashArea">
<option value="" selected disabled>AREA</option>
<option value="Red">RED</option>
<option value="Blue">BLUE</option>
<option value="Green">GREEN</option>
</select>
<br>
<input class="" type="text" name="dashAddress" placeholder="Address" />
<input type="checkbox" id="checkbox1" name="dash_enable">
<br>
<input type="submit" class="" id="saveMemberBtn" value="SAVE" />
</form>
Since your SAVE button is a type="submit", you would not need a click handler to capture it and test validity. The submithandler built into the plugin is already doing this for you.
$('#updateMemberForm').validate({
submitHandler: function(form) { // only fires when valid
var serialize = $("#updateMemberForm").serialize();
$("#test").text(serialize);
console.log(serialize);
// AJAX goes here
return false;
}
});
DEMO: https://jsfiddle.net/rsfonzL7/
As already mentioned in the comments, when a checkbox is not checked, nothing is sent in the query string, and this is handled on the server side. This has nothing to do with jQuery Validate or .serialize()... this is just how form data is constructed and sent, no matter the method.
Related
I want to check if the Value enter in the input is in the datalist.
If not i inform that the value is not in the list, I write something but the submit is done anyway, i miss something ?
Edit: I edit to have a trial form. If i enter productD the submit can't not be done becuase is not in the list defined.
<tbody>
<div class="fichetechniquediv">
<form action="{% url 'createdfichetechnique' %}" method='post' onclick="return myCheckFunction(this)">
<h1>Create the technical Sheet</h1>
<br><br>
<div class="divlot">
<label for="lot">Enter your Lot:</label>
<input type="text" id="lot" name="lot" required minlength="7" oninput="this.value = this.value.toUpperCase()">
</div>
<br><br>
<div class="divproduct">
<label for="productlist">Enter or Select Product:</label>
<input type="text" name="Product" id="productlist" list="productslist" label="'Enter or Select your Product:">
<datalist id="productslist">
<option value="productA">productA</option>
<option value="productB">productB</option>
<option value="productC">productC</option>
</datalist>
</div>
<br><br>
<input class="buttonsave" type="submit" value="Create" name="submit">
</form>
</div>
</tbody>
<script>
function myCheckFunction(form) {
var list = document.getElementsById("productslist");// get the values that are currently under the datalist tag in option tags
var val = document.getElementsByName("Product");// get the user input
if( list.include(val)){ // compare the options with the user input
submit(form)}// if one is equal with the user input submit the form with the method submit();
else{
return false// else don't submit the form, the user will have to change his input
}
}
</script>
Example productD
const list = document.querySelector("#productslist")
const btn = document.querySelector(".buttonsave")
console.log(list.options.length)
if(list.options.length <= 0 ){
btn.disabled = true
}else {
btn.disabled = false
}
Check if is any products. If the script can't see any products disable the button to send. I hope I helped
You cannot use include for DOM elements like you do.
Also you have duplicate IDs
Instead do this:
const list = document.querySelectorAll("productslist option")
document.getElementById("myForm").addEventListener("submit", function(e) {
const val = document.getElementById("productlistInput").value
const found = [...list].find(opt => opt.value===val)
if (!found) {
alert("Please choose an existing value");
e.preventDefault();
}
})
<form id="myForm" action="..." method='post'>
<h1>Create the technical Sheet</h1>
<br><br>
<div class="divlot">
<label for="lot">Enter your Lot:</label>
<input type="text" id="lot" name="lot" required minlength="7" oninput="this.value = this.value.toUpperCase()">
</div>
<br><br>
<div class="divproduct">
<label for="productlist">Enter or Select Product:</label>
<input type="text" name="Product" id="productlistInput" list="productslist" label="'Enter or Select your Product:">
<datalist id="productslist">
<option value="prod1">Product 1</option>
<option value="prod2">Product 2</option>
</datalist>
</div>
<br><br>
<input class="buttonsave" type="submit" value="Create" name="submit">
</form>
There are two things going wrong in this:
document.getElementsById("productslist"); is incorrect. The function is getElementById(...)
document.getElementById("productslist"); will get you an HTML nodes, not the values.
One of the ways to get the values is:
const values = [];
Array
.from(document.getElementById("productslist").options)
.forEach((option) => {
values.push(option.value);
}
Now that you have the values in the values array, you can look it up to check if the value is already present.
My form is as follows:
I am using nodejs and javascript.And here depending on the value selected by the user from the dropdown list,accordingly that url is called.Like for the movie options:"localhost:3000/new" will be called.This works fine! but it is simply getting redirected to the url without any parameters of the form .I want the form values also to be passed along with the url .How can this be done?
Please help?
Thanks :)
<form>
<input type="text" name="currentloc" class="textbox" id="currentloc"
placeholder="Your location"/>
<input type="text" name="destloc" id="destloc" autofocus="autofocus"
class="textbox" placeholder="Enter the destination"/>
First Event : <select name="events" onchange="location = this.value;">
<option value="" >Select your first event</option><br><br>
<option value="/new" name="movies" id="movie" method="get">Watch a
Movie</option>
<option value="/food" name="restuarantis" id="rest" >Restaurant table
booking</option>
</select>
</form>
Here is what you could do in your form:
<body>
<form name="pickerForm" method="GET" action="">
<input type="text" name="currentloc" class="textbox" id="currentloc" placeholder="Your location" />
<input type="text" name="destloc" id="destloc" autofocus="autofocus" class="textbox" placeholder="Enter the destination" />
First Event :
<select name="events" onchange="return loadCorrectPage(event);">
<option value="" >Select your first event</option><br><br>
<option value="/new" name="movies" id="movie" method="get">Watch a Movie</option>
<option value="/food" name="restuarantis" id="rest" >Restaurant table booking</option>
</select>
</form>
<script>
function loadCorrectPage(event) {
event.preventDefault();
console.log(event.target.value);
document.forms['pickerForm'].action = event.target.value;
document.forms['pickerForm'].submit();
}
</script>
</body>
document.forms['pickerForm'] matches the form element <form name="pickerForm" because of name=
You have to use method="GET" to send the data in the form to your node.js backend and make them available on req.query
We are using action="" because we will set it using JavaScript
When a change happens in your select element, we run the function loadCorrectPage() and we pass in event which is a variable that holds the data about the onchange event
Then, we need to create the function
event.preventDefault() is probably unnecessary here, but good to understand how it works if you don't
event.target.value holds the value of the changed option
We update document.forms['pickerForm'].action to the changed option, which means action="" is now either action="/new" or action="/food"
We call document.forms['pickerForm'].submit() which submits the form!
Now, in your node.js backend, you need corresponding routes. If you are using Express, they will look like this:
app.get('/new', function(req, res) {
console.log('\nSomeone just picked movies!');
console.log('Current location:', req.query.currentloc);
console.log('Destination:', req.query.destloc);
});
app.get('/food', function(req, res) {
console.log('\nSomeone just picked restaurants!');
console.log('Current location:', req.query.currentloc);
console.log('Destination:', req.query.destloc);
});
So this has been driving me nuts, im looking for a solution that will fill a input field from what ever selection is made from a drop down.
My current working solution (that does not include a drop down) is as follows :
<form method="link" action="dualstream/index.html">
<input value = 'apolloz' name="stream1" placeholder="" required="required"
autofocus="autofocus" />
<input type="submit" class="button" value="Click to watch the stream" />
</form>
So that auto fills the text field with "apolloz" then when you press submit it takes you to the relevant page which uses the word apolloz.
Im looking for a solution that you can select the streamer from a drop down list, select it and that option fills the text field, and you can then submit.
Im sure this is javascript based as i have seen similar things which use numerical values.
Sorry if this is a bit vague, but any and all help is much appreciated.
try this
<form method="link" action="dualstream/index.html">
<input value = 'apolloz' id="txt" name="stream1" placeholder="" required="required"
autofocus="autofocus" />
<select id="mySelect" onchange="selectionchange();">
<option value="abc" >abc</option>
<option value="xyz" >xyz</option>
</select>
<input type="submit" class="button" value="Click to watch the stream" />
</form>
and add following javascript function
function selectionchange()
{
var e = document.getElementById("mySelect");
var str = e.options[e.selectedIndex].value;
document.getElementById('txt').value = str;
}
This is simple, if you use jquery you can do this
$(function(){
$("#your_select").change(function(){
$("#your_input").val($('#your_select option:selected').val())
});
});
u can also do this using just javascript
on the onchange function of your select u can call a function that will put the selected value in your input
like
<select id="element1" onchange="pickvalue()"/>
<option>asad </option>
<option>asad2 </option>
</select>
and your pickvalue function can look something like this
function pickvalue()
{
document.getElementById('yourinputid').value = document.getElementById('element1').value
}
Suppose you have a selectbox #selectid then,
$("#selectid").live("change", function() { <br>
$("#stream1").val($(this).find("option:selected").attr("value")); <br>
});
so i am using the play framework and I'm try to create multiple submit buttons that call the one form:
So what I have is a list of strings, and i would like to create two buttons that will go back to the server and complete an event, the first is send the second is cancel. What i would like to also do is set the source value equal to what is selected in the foo select object. How would I go about doing this? Do i need to create a javascript even that is fired from the form and then get the var inside that function and then fire off the submit? Im not 100% familiar with play framework and scala, so im not sure if i can get it somehow inside this code without using a new method.
#(myList: List[String], theForm: Form[Obj])
#import helper._
#main("myVar Controller") {
<select id="foo">
</select>
<table border="1">
<tr>
#for(myVar <- myList) {
<td>#myVar
#form(routes.Application.method()) {
<div id="hiddenForm" style="visibility:hidden">
<input type="text" name="commandID" id="commandID" value="10" /> //Send Code
<input type="text" name="source" id="source" value=**"Put selected value of foo here" />**
<input type="text" name="destination" id="destination" value="#myVar" />
</div>
<input type="submit" value="Send" />
}
#form(routes.Application.method()) {
<div id="hiddenForm" style="visibility:hidden">
<input type="text" name="commandID" id="commandID" value="18" /> //Undo code
<input type="text" name="source" id="source" value=**"Put selected value of foo here" />**
<input type="text" name="destination" id="destination" value="#myVar" />
</div>
<input type="submit" value="Undo" />
}
</td>
}
</tr>
</table>
}
First of all, the html isn't valid.
You should first make sure that there aren't elements that have the same id.
You have to use javascript to change a value in your form.
I'm not familiar with scalar or playframework, but if they allow you to use jQuery, I recommend the following solution.
$("#foo").bind("change", function(){$("#source").val($("#foo").val()));});
example:
http://jsfiddle.net/RubenJonker/a8a8p/5
If they don't allow you to use jQuery, then you should put some javascript in the onchange event of the select.
<select onchange="document.getElementById('source').value = this.value">
</select>
example:
http://jsfiddle.net/RubenJonker/a8a8p/4
Incase anyone else has this problem I used the following to solve my problem: Thanks Ruup as your code was the reason why I solved the problem
html:
<select id="foo" >
<option></option>
<option value="test">test</option>
</select>
<input type="text" value="" name="field" id="field" />
and javascript:
$(document).ready(function() {
obj = document.getElementById("foo");
obj.onchange = function()
{
var elements = document.getElementsByName('field');
for (i=0;i<elements.length;i++)
{
elements[i].value = $('#foo').val();
}
}; });
I am having trouble with some Ajax functionality.
I have a single dropdown that needs to update a record when the option changes. Here is a snippet of the Javascript:
function changeResponsibleParty(selectObj, targetDiv){
var idx = selectObj.selectedIndex;
var which = selectObj.options[idx].value;
target = document.getElementById(targetDiv);
target.value = which;
document.forms["changeResponsibleParty"].submit();
}
And the HTML:
<form name="changeResponsibleParty" action="javascript:changeResponsiblePartyAjax('project_todos');" method="post" style="display:inline;">
<input type="hidden" name="todo_id" id="todo_id_15" value="15" />
<input type="hidden" name="project_id" id="project_id_15" value="2" />
<input type="hidden" name="user_id" id="user_id_15" value="" />
<select name="user_id_pick" id="user_id_pick_15" onchange="changeResponsibleParty(this, 'user_id_15');" style="border:0;">
<option value="0">Anyone</option>
<option value="1" selected="selected">Allen McCabe</option>
<option value="2">Thomas Martinez</option>
</select>
</form>
I am using the function to update a hidden input element because for some reason, the tag was posting 1 regardless of which option I chose (1 is my user_id, which I set as selected if the database record value is 1.
Can anyone see what is wrong here?
You use changeResponsibleParty as name for the form and also as name for the function, which will cause conflicts. Rename one of them.