I have a form to create a true/false question. I am trying to have a button to toggle the value of a text_field from true and false. (I really do not care what way it is done, I just want the user to be able to easily change the answer to true or false.
This is what I have, it only toggles one time to false and only works when I click the text field not the button. I am trying to learn javascript, so bear with me...
<%= f.label :content, "Answer" %>
<%= f.text_field :content, :value => 'True', :readonly => true, :class => "d-id", :id => "answer" %>
<%= button_tag "Toggle True/False", :id => "answer", :class => "btn btn-small btn-inverse", :type => "button" %>
<script>
function checkAnswer() {
if ($("#answer").val('False'))
{
$("#answer").val('True');
}
if ($("#answer").val('True'))
{
$("#answer").val('False');
}
}
$(document).ready(function(){
$('#answer').click(function () {
checkAnswer();
});
})
</script>
http://jsfiddle.net/jayblanchard/ene5w/
I cleaned up your syntax some and came up with this -
function checkAnswer() {
var answer = $('#answer').val();
if ('False' == answer) {
$("#answer").val('True');
} else {
$("#answer").val('False');
}
}
Also, you have two elements with the same ID which is not allowed in an HTML page. You'll get wonky results. You could change these to classes.
Changed to a button instead of a link - http://jsfiddle.net/jayblanchard/ene5w/1/
Change the text of the button - http://jsfiddle.net/jayblanchard/ene5w/2/
Try this:
if ($("#answer").val() === 'False') {
$("#answer").val('True');
} else {
$("#answer").val('False');
}
Related
Basically I already have a piece of coffeescript that animates a drop down menu:
menu_in = -> $('.cart_pulldown').slideDown(250)
menu_out = -> $('.cart_pulldown').slideU(150)
$('#store_menu').hoverIntent(over: menu_in, out: menu_out, timeout: 150)
And I want to tie this to the add-to-cart-button action so that the menu slideDown/slideUp sequence happens when a user adds to their cart, heres that js code:
function set_product_page_variant_state() {
var varel = $('div#product-social-links');
var cart_link = $("#add-to-cart-button");
if(varel && cart_link) {
if(variant_id = varel.attr('data-variant-id')) {
$.post('/flash_sales/get_state.json', {'variant_ids[]': [variant_id]}, function(data) {
var state = data[variant_id];
if(state) {
if(state=='on_hold') {
cart_link.text("On Hold").show();
} else if(state=='in_my_cart') {
// TODO: this is funking ugly and slow to load, this whole thing needs a good old fashion refactorin'.
cart_link.text("In My Cart")
.hide()
.after("<a href='/cart' class='action-button add_to_cart' id='#add-to-cart-button'>In My Cart</a>")
.remove()
} else if(state=='available') {
cart_link.removeAttr('disabled').show();
} else if(state=='sold_out') {
cart_link.text("Sold Out").show()
} else {
// something went wrong, enable the button
cart_link.removeAttr('disabled').show()
}
} else { cart_link.removeAttr('disabled').show() }
});
} else { cart_link.removeAttr('disabled').show() }
}
}
and just to be thorough, here is the associated html:
<div id="cart-form">
<%= form_for :order, :url => spree.populate_orders_url do |f| %>
<div id="inside-product-cart-form" itemprop="offers" itemscope itemtype="http://schema.org/Offer">
<% if #product.price %>
<div>
<div class="add-to-cart">
<%= hidden_field_tag "variants[#{#variant.id}]", 1 %>
<%= button_tag "Add to Cart", :class => "hidden action-button add_to_cart", :type => :submit, :disabled => true, :id => "add-to-cart-button" %>
</div>
</div>
<% end %>
</div>
<% end %>
</div>
Any advice is greatly appreciated, thanks in advance!
You can use jQuery delegate events in your Coffeescript file. For example, to show the menu for 500ms before triggering menu_out:
$(document).on 'click', '#add-to-cart-button', (event) ->
menu_in()
setTimeout 500, menu_out
Since CoffeeScript puts your code in a closure you need to manually attach global variables to the window, like window.menu_in = -> ...
I have a form where I need the user to select (with radio buttons) an option that will determine the next form field beneath it. In this case, their post can be a post or a revision of a post. Thus, selecting 'post' will show a title field (to name the post) and selecting 'revision' will show a select list of existing posts to choose from (the title will be inherited).
_form.html.erb
<!--Form inputs-->
<%= f.collection_radio_buttons :is_revision, [[false, 'Post'] ,[true, 'Revision']], :first, :last %>
<%= f.input :revision_id, collection: #originals, :input_html => {:id => 'revision'} %>
<%= f.input :title, :input_html => { :maxlength => '50', :placeholder => 'Title', :id => 'title'} %>
<!--Javascript-->
<script type="text/javascript">
$('input[name="post[is_revision]"]').on("change", function(){
if ( $("#post_is_revision_true").attr("checked")){
$("#title").hide();
$("#revision").show();
}
if ( $("#post_is_revision_false").attr("checked")){
$("#revision").hide();
$("#title").show();
}
});
</script>
I should mention that this works fine when hiding and showing one field, yet when selecting the other radio button nothing changes. I feel the logic is correct (although I'm not the strongest with JS) but I can't seem to get this.
EDIT: I made a few jQuery errors. Also, here is a jsFiddle example
Try this.
$('input[name="post[is_revision"]').change(function() {
var selected = $('input:checked[name="post[is_revision]"]').val();
if(selected == 'revision') {
$('#title').hide();
$('#revision').show();
} else if(selected == 'new_post') {
$('#revision').hide();
$('#title').show();
}
});
Another way to do it, smaller but more confusing:
$('input[name="post[is_revision"]').change(function() {
var is_revision = $('input:checked[name="post[is_revision]"]').val() == "revision";
$('#title').toggle(!is_revision);
$('#revision').toggle(is_revision);
});
If one will always be selected first, you could condense it to this:
$('input[name="post[is_revision"]').change(function() {
$('#title').toggle();
$('#revision').toggle();
});
Or for kicks and giggles and slides:
$('input[name="post[is_revision"]').change(function() {
$('#title').slideToggle();
$('#revision').slideToggle();
});
Comment if you have problems with any.
if i have this as my form
<%= form_for #rating, :id =>"ratingForm" do |f| %>
<%= f.hidden_field :ratings, :value => '' %>
<%= f.hidden_field :user_id, :value => current_user.id %>
<%= f.hidden_field :recipe_id, :value => #recipe.id %>
<div class="rateit" id="rateit10">
</div>
<%= f.submit "Submit" %>
<% end %>
How do i pass the value of the content within this div
<div class="rateit" id="rateit10">
</div>
if i use this jquery I can get the value of rateit10
$("#rateit10").bind('rated', function() {
$(this).rateit('value');
});
The value derives from clicking upon a set of stars, im trying to implement a rating system in rails using the Rateit plugin
This will pass a hash to your controller method:
function pass_to_controller(){
var rate_value = $("#ratings").value();
var user_id = $("#user_id").value(); /*you already have access to this through current_user.id */
var recipe_id = $("#recipe_id").value();
$.ajax({
type: "Get",
url: "path_to_your_controller_action_here",
timeout: 5000,
data: {rating : rate_value, user : user_id, recipe : recipe_id }
}).done(function(response){//do your response here});
}
You can't directly pass to the model - that circumvents the whole thought process behind MVC. So the best way to do it is to use ajax, pass it to your controller method, then if you need to do something in your database call your model method.
The advantage of using ajax like this is that it won't reload your page when someone rates something.
The easiest way is to trigger an update of your hidden field when the user click on a star, rather than read the value of the stars when the form is submitted.
I should add a onnclick event on the stars to update the hidden field. To do this, add an ID to your hidden field with :id => "my_hidden_field" to name it.
Then, trigger a javascript function when the user click on a star :
$("#second_star").click(function() {
$("my_hidden_field").value = 2;
});
To show text inside div using javascript:
divObj = document.getElementById("rateit10");
if ( divObj ){
if ( divObj.textContent ){ //FF
alert ( divObj.textContent );
}else{ //IE
alert ( divObj.innerText ); //alert ( divObj.innerHTML );
}
}
To show innerdiv inside div using javascript:
myDivObj = document.getElementById("rateit10");
if ( myDivObj ) {
alert ( myDivObj.innerHTML );
}else{
alert ( "Text Found" );
}
To show text inside div using jquery
$(function(){
var txt = $('#rateit10').text();
alert(txt);
};
I have the following form on a site
<% form_tag({ :action => :subid}, :id=>'run_report', :name => 'run_report') do %>
Beginning Date <%= date_select("post", "start_date", :start_year => 2010,:order => [:month, :day, :year]) %><br />
End Date <%= date_select("post", "end_date", :start_year => 2010,:order => [:month, :day, :year]) %><br />
<%= submit_tag 'Run', :name => "submit", :class => "submit_btn" %>
<% end %>
I want to add another button called Generate that is passed the same variables (start_date and end_date) as the form below but calls the action generate instead of run. Ideally I'd like to do this without having to have two duplicate forms.
Any help is appreciated.
or you may bind your button onclick action Something like
$("#your_button_id").click(function() {
$.post("second_url", $("#your_form_id").serialize());
return true;
});
It's possible with a javascript. In the view you can use name attribute or html5 data-attribute as I do below. The main idea is that it's necessary to store somewhere url to proper form action.
<% form_tag(:id=>'run_report', :name => 'run_report') do %>
<%= submit_tag 'Run', :name => "submit", :data-action => "#{url_for(action1)}", :class => "submit_btn" %>
<%= submit_tag 'Generate', :name => "generate", :data-action => "#{url_for(action2)}", :class => "submit_btn" %>
<% end %>
Simple JQuery script (should work but not tested):
var $form = $('#run_report);
$('#run_report :submit').click(function() {
$form.attr('action', $(this).attr('data-action')).addClass('ready').submit();
});
$form.submit(function(e){
if(!$form.hasClass('ready')) {
e.preventDefault();
});
The trick is that while form has not class ready, it won't be submitted. And you add this class after setting proper form action.
This works for me when I initialize hidden form fields with values depending on what button was clicked but with the same form action. Though the approach in your case can be the same. Hope this direction will help you.
In TextField of Ruby Code, I want to check whether the specified class is applied or not, on blur event. Please suggest some technique or way. Sample code is given below used by me.
Ruby Code for TextField::
<%=f.text_field :Username, :size=>4, :tabindex=>2, :class=>class_name,
:autocomplete => "off", :onblur=> $$$$$ %>
Suppose class_name : 'changeView' is applied on above textfield, then I have to detect this particular class & replace by another one like 'changeExtraview'. By using any of the javascript, we can replace that class name but suggest if you have any better option.
Thanks
Just a guessed answer...
So your class_name might be contain a value of changeView, and if in the case, you want to replace the changeView class name to changeExtraview, right?
If it is, then the following should be ok:
<%=f.text_field :Username, :size=>4, :tabindex=>2, :class=>class_name.gsub(/changeView/, "changeExtraview"), :autocomplete => "off", :onblur=> $$$$$ %>
========================
Another try:
<%=
f.text_field :Username, :size=>4, :tabindex=>2, :class=>class_name, :autocomplete => "off",
:onblur => "if($(this).hasClass('changeView')) {$(this).removeClass('changeView'); $(this).addClass('changeExtraview')}"
%>
========================
As #Faisal pointed out, using binding in JS side would be better. Although the answer was long time ago, I decided to update the answer again:
<%= f.text_field :Username, :size => 4, :tabindex => 2, :class => class_name, :autocomplete => "off" %>
And in any ways (I use content_for in this example), add the following js code:
<%= content_for :javascripts do %>
<script type="text/javascript">
jQuery(document).ready(function($) {
$("<%= class_name %>").bind("blur", function() {
var $this = $(this);
if ($this.hasClass('changeView')) {
$this.removeClass('changeView');
$this.addClass('changeExtraView');
}
});
});
</script>
<% end %>
Note that the above code requires you have <%= yield :javascripts %> in your layout file,