Don’t leave this page cause I said so dialog

Rails

I have a process where I create an object on one screen, and then in the next screen add some information to that object.

Problem is, if you navigate away from that second page I have an object that has no important info attached to it.

My process is a wizard approach to setting up a new account, which only really has a name, and then the account has users and billing info attached to it in separate models/tables. So give it a name and save it, redirect to the next screen and add users and billing.

So I want the “Hey you! Don’t navigate away” dialog to appear on all but a few links and form submits on the add users and billing page. Its actually super easy.


Take a look at this very nicely formated gist
I would put this stuff in code tags and display it here but it looks like crap and I can’t embed gists unless I pay wordpress. And wordpress stripped all my erb and html tags so just go look at the gist.

Get the value of a selected option with Javascript

Rails, Ruby

Ok, there were no good straight forward references on google. So…here’s how you do it…

I have a select box…

<select>
<option value=1>One</option>
<option value=2>Two</option>
</select>

when the user selects any option I wan to get the value of the option (I’m trying to evaluate the option value and then based on the selection, show the user another part of the form..)

So in your select tag you drop in:

onchange="this.options[this.selectedIndex].value"

  • “onchange=” – this is triggered when the user changes the option in a select box (onclick is not supported in IE)
  • “this.options” – this gets you the array of options in your select tag, here this would be: [1,2]
  • “this.selectedIndex” – this gets you the index of the item selected…so if the user selects option “One” this.selectedIndex=0, for the first element in the array of options.
  • “.value” – this just gets me the value of the option, here that’s either 1 or 2. If you want the text (“One” or “Two”) use “.text”

So lets put it together (i’ll add my conditional showing of another piece of the form too):

<select onchange="if( this.options[this.selectedIndex].value=='1')
{Element.show('another_piece')}
else
{Element.hide('another_piece'}">
<option value=1>One</option>
<option value=2>Two</option>
</select>
;