Auto-submitting HTML select drop-down in Rails - javascript

I have a simple drop-down menu using HTML's select tag. The code for the select tag becomes:
<select name="menu_id" id="menu_id">
<option selected="selected" value="1">Dinner</option>
<option value="2">Lunch</option>
</select>
In my menu.js.coffee file I have:
$("select#menu_id").change(-> $(this).closest("form").submit())
This becomes menu.js:
(function() {
$("select#menu_id").change(function() {
return $(this).closest("form").submit();
});
}).call(this);
The problem is changing the select menu doesn't submit the form! It doesn't even enter the above menu.js code (I place breakpoints there and it never enters after selecting a menu option).
If I then just copy the inside of the above (function() {, and I paste it into the Firebug or Chrome console, then it runs as expected and changing the menu does in fact submit the form. So how am I supposed to write the coffeescript code in rails to allow forms to be submitted when a select menu is changed?
I'm using Rails 3.2.8.

Try putting your code inside the $(document).ready () -> block.
$(document).ready () ->
$("select#menu_id").change(-> $(this).closest("form").submit())

document.ready functions use only when page reload occur.
you may use separate function and call using onchange.
Example:
<select name="menu_id" id="menu_id" onchange="callThisFunction()">
<option selected="selected" value="1">Dinner</option>
<option value="2">Lunch</option>
</select>
<form name="myform"></form>
function callThisFunction()
{
document.forms["myform"].submit();
}

Related

select element validation doesn't working in JavaScript

I have an Index.html file in which I am giving two options two different values (Yes or No).
Issue:
I want to validate with those values in JS but when I am doing it can't hold the value of that.
What I Have:
Index.html:
<select id="sel">
<option value="yes" >Yes</option>
<option value="no" >No</option>
</select>
Valid.js:
var sel=document.getElementById("sel").value;
localStorage.setItem("sel", sel);
Calculate.js:
I have to validated here I have connected Confirm.html with form action in Index.html.
In confirm.html I am loading init() method of calculate.js
var sel = localStorage.getItem("sel");
Assuming that the code for the validation and calculation are both in different files I would highly recommend checking the order in which you load the scripts in your HTML file, alternatively you could just attach an event listener to the selection tag which would trigger each time the user changes the selection like so;
document
.getElementById('sel')
.addEventListener('change', function(event) {
localStorage.setItem("sel", this.value);
})
and then when validating input check whether the "sel" value is present within the localStorage just as you originally planned.

Getting form’s select list values before form’s submission

I want to get the values from selected “select list option fields” in a form, before submit the form, and use them as variables in my web page.
For example:
I have the form bellow:
<form>
<select name="test">
<option value="111">Something</option>
<option value="222">Something</option>
<option value="333">Something</option>
</select>
</form>
I want to know if my web page user has selected the 111 or the 222 or the 333 value and after that to do something like that:
<%
If user selected the value "111" then
Do something...
Else
Do something else...
End If
%>
Is there any possible way to do something like that before form’s submission?
After a long search I did, I learned that what I need can be done with JavaScript, but unfortunately I am completely ignorant with JavaScript. Could anyone guides me?
You can't use form values as ASP variables without submitting them to the server because ASP runs on the server to do all it's stuff. JavaScript will run in the browser so can perform functions such as calculations without submitting the form to the server.
If you simply want to display the selected form options on the page then us can use JavaScript (or jQuery if you have that running on the page).
e.g.
<script>
function showValue(s) {
document.getElementById('myid').innerHTML = s;
}
</script>
<form>
<select name="test" onChange="showValue(this.value);">
<option value="111">Something 111</option>
<option value="222">Something 222</option>
<option value="333">Something 333</option>
</select>
</form>
<div id="myid"></div>
If you want to process the selection in some way before submitting the form to either set another form field, or display some calculation you need to either write the calculation function in JavaScript or use AJAX (as suggested by ThatGuyInIT) to get another ASP page to do the processing for you and bring the results back to your page.

Enable field function triggers after second function is called

I need some help with sequencing (not sure if this is the right term) two jQuery functions so that both can co-exist together.
What I am trying to do is to add a new functionality that makes a field uneditable to the users, like disabled="disabled". Catch is that if I only apply disabled="disabled" to the filed the form will not send its value with the form submit.
Therefore, I have written some JS code, which enables the fields prior submitting and permits that their values are sent when form is submitted.
All works fine once the page is loaded.
Problem is when the user leaves one of the mandatory fields blank and tries to submit the form. Then there is another jQuery that fires - to validate the field contents.
This second validation function triggers the enable field function and all fields become editable again.
Need some help on how to prevent the second function to override the enable one.
Here is the code - the enable function is placed right before the form like this:
<script>
jQuery(function($) {
$('form').bind('submit', function() {
$(this).find(':input').removeAttr('disabled');
});
});
</script>
<form name="RegFrm" id="RegFrm" action="" method="post">
<select class="validate[required] text-input" disabled="disabled">
<option value="">Please Select</option>
</select>
<input name="sbtFrm" type="submit" value="Submit" />
</form>
And here is the second field validation function that is placed on a separate file. It is being invoked from files_include.php every time the page loads:
var genVar = jQuery.noConflict();
genVar(document).ready(function(){
genVar("#RegFrm").validationEngine();
});
How can I prevent the second function triggers the first one?
Thank you?
Thank you all for the comments. Although, no solution proposed you guys gave me an idea how to fix it.
I basically decided to check on form submit if form validates and only if true, then the enable function triggers.
This is the code:
jQuery(function($) {
$('form').bind('submit', function() {
if($("#RegFrm").validationEngine('validate')){
$(this).find(':input').removeAttr('disabled');
};
});
});

Jquery val() always grabs first select value no matter which is selected

I'm using Jquery to allow users to upload an image via Ajax in a form (the image uploads before the form is actually submitted). I've added the ability to add a watermark to each image that is uploaded (this is done in upload_image.php) this part works fine.
The user can select where they want the watermark to be placed on their image via a form select. I'm using Jquery's .val() to grab the value of the id="watermark" select and add it as a query string value to be passed to upload_image.php.
The problem is that it always passes the first select value no matter what I actually select in the form. I tried putting it in a function (thought it was grabbing the value on page load) no luck there. I changed the select to radio buttons. It still grabs the value of the first radio button on the page; no matter what you select.
Here is the portion of the script that handles this:
<script type="text/javascript" >
$(function(){
// build URL to php upload script with watermark placement
function setWatermark() {
var uploadUrl = 'http://www.mysite.com/upload_image.php?w=';
var watermarkValue = $('#watermark').val();
var watermarkUrl = uploadUrl + watermarkValue;
return watermarkUrl;
}
var btnUpload=$('#upload');
new AjaxUpload(btnUpload, {
action: setWatermark(),
name: 'uploadfile',
});
});
</script>
This is the form (with irrelevant fields removed):
<form id="image_form" action="this_form.php" method="post" enctype="multipart/form-data">
<select id="watermark">
<option value="top_left">Top Left</option>
<option value="top_right">Top Right</option>
<option value="center">Center</option>
<option value="bottom_left">Bottom Left</option>
<option value="bottom_right">Bottom Right</option>
</select>
<div id="upload" ><span><img src="upload_button.jpg" /></span></div>
</form>
To execute this code:
new AjaxUpload(btnUpload, {
action: setWatermark(),
name: 'uploadfile',
});
The browser must first construct the arguments to pass to the constructor. To construct the second argument, the object, it must call setWatermark to get the value for the action property. This is where your problem is; setWatermark is being called when the AjaxUpload object is created.
I don't know what AjaxUpload is, but you'll have to find a way to get it to call a function when it needs the action rather than it being provided as a constant in the options.

Javascript - form select element open url in new window and submit form

UPDATED - please read further details below original question
I have a select form element with various urls, that I want to open in a new window when selected - to do this I have the following code in the element's onchange event:
window.open(this.options[this.selectedIndex].value,'_blank');
This works fine. But I also want to submit the form when changing this select element value - I've tried various things, but I can't seem to get it to work.
I have jquery, so if it's easier to achieve via that then that's fine.
Update - I've just realised there is another issue with the above, because some of the urls are actually used to generate and output pdfs, and these do not work - they open and then immediately close (at least in IE7).
UPDATE 07/05/09 - I've now opened a bounty for this question as I really need to come up with a working solution. I did originally get around the issue by displaying links instead of a form select element, but this is no longer feasible.
The reason I need the above is that I have a large number of files that might need to be viewed / printed, too many to reasonably display as a list of links. I need to submit the form to record the fact a particular file has been viewed / printed, then display a log of the file history on the form - I'm comfortable with achieving this side of things, so don't require assistance there, but I thought it would help to place the context.
So, to clarify my requirements - I need a form select element and 'View' button that when clicked will not only launch a file download in a new window (note the above issue I faced when these files were PDFs), but also submit the form that contains the select element.
Here ya go
<script type="text/javascript">
$(function() {
$("#selectElement").change(function() {
if ($(this).val()) {
window.open($(this).val(), '_blank');
$("#formElement").submit();
}
});
// just to be sure that it is submitting, remove this code
$("#formElement").submit(function() {
alert('submitting ... ');
});
});
</script>
<form id="formElement" method="get" action="#">
<select id="selectElement">
<option></option>
<option value="http://www.deviantnation.com/">View Site 1</option>
<option value="http://stackoverflow.com/">View Site 2</option>
<option value="http://serverfault.com/">View Site 3</option>
</select>
</form>
You can use this.form.submit() to trigger the form submit:
<script language="javascript">
function myChangeHandler() {
window.open(this.options[this.selectedIndex].value, '_blank');
this.form.submit();
}
</script>
<select onchange="myChangeHandler.apply(this)">
...
</select>
Just tested Aron's example and it works fine, so I would suggest the error you are getting is from code outside of your onchange event. Try the below working example and see if you get the same error.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE> Example onchange and submit </TITLE>
<script language="javascript">
function myChangeHandler()
{
window.open(this.options[this.selectedIndex].value, '_blank');
this.form.submit();
}
</script>
</HEAD>
<BODY>
<form id="myform1" action="test.html">
<select onchange="myChangeHandler.apply(this)">
<option>Please select....</option>
<option value="http://stackoverflow.com">Stackoverflow</option>
<option value="http://twitter.com">Twitter</option>
</select>
</form>
</BODY>
</HTML>
Basede on what you've described, your markup probably looks something like this:
<form ...>
<input name="submit" ...>
...
</form>
Because browser tradition is to add to the form element's object (as properties) inputs' names, the "submit" property from the input masks the form's inherent "submit" property or method. You can correct this by renaming, even temporarily, the input element (assuming there's just the one):
form_object.elements['submit'].name = 'notsubmit';
form_object.submit();
If there are more than one -- eg, a series of radio buttons named "submit" for some reason -- then .elements['submit'] should be an element collection, which is like an array, which you can loop over to do the same thing.
You know you can set a target attribute for the form?
<form target="_blank" method="post">
<select onchange="load()">
...
</select>
</form>
<script>
load() {
document.forms[0].action = this.value;
document.forms[0].submit();
}
</script>
Forgive the probably bad Javascript. I tend to do more jQuery these days so I'm rusty on vanilla Javascript. But you get the general idea.
While I'm not familiar with jQuery, you should be able to do something like this (Prototype-style):
$('select-field').observe('change',function(event){
window.open(this.options[this.selectedIndex].value,'_blank');
this.form.submit();
}
Though I have had a few odd issues with submitting forms with Javascript before, so if that doesn't work you could try calling click() or the equivalent of fireEvent('click') on your form's submit button, like so:
$('submit-button').fireEvent('click');

Categories

Resources