clear input after search - javascript

I have a search box on my site. The search works well. I'd like the search field to clear after you submit a search. I have it working to clear onclick but the onsubmit doesn't work. It is definitely submitting a search because I can see the results.
js
<script type="text/javascript">
function clearDefault(el) {
if (el.defaultValue==el.value) el.value = ""
}
function clearText(thefield){
if (thefield.defaultValue==thefield.value)
thefield.value = ""
}
</script>
view
<%= form_tag guidelines_path, :class => 'navbar-search pull-right', :onSubmit=>"clearText(this)",:method => :get do %>
<%= text_field_tag :search, params[:search], :class => 'search-query', :placeholder=>"Search", :ONFOCUS=>"clearDefault(this)" %> <% end %
>

Th onsubmit isn't an event of a text field but rather the form it belongs to. If you move your onsubmit attribute to the form, it should clear it.

Rather than pass the field as a parameter, why not just fetch the field by it's class? So using jquery:
function clearText(){
search = $('.search-query');
if (search.defaultValue==search.value)
search.value = ""
}
If you can't use jQuery for some reason you could try and assign the form field an ID and use document.getElementById() instead?

Related

Ruby on Rails reset value back to null

Following were my view:
<div class="col-xs-3">
<%= f.select(:require_booking, get_advance_booking.collect {|p| [ p[:require_booking], p[:require_booking] ] }, {include_blank: false} , :class => 'form-control') %>
</div>
<div class="col-xs-3">
<%= f.text_field :require_days, :class => 'form-control advance-booking', :placeholder => 'How many days?', :disabled=>true%>
</div>
And here is my application_helper.rb
def get_advance_booking
ret = [{:require_booking => 'Yes'},{:require_booking => 'No'}]
end
Following were my product.rb model
class Product < ActiveRecord::Base
enum require_booking: {
No: 0,
Yes: 1
}
end
Now the Issues is if I select an option of Yes the text field will be enabled and user can enter value. In edit mode, if I select an option No how can I set the text field value back to NULL and save to db? Currently, even though I set the value NO I still get my previously set value. Thanks!!
You only can do that with javascript changing the value field of select.
Example:
Supose that your code generate the following html:
<input type="select" value="Yes"></input>
<input type="text" value="EditValue"></input>
For solve this question you need a javascript(jQuery) code like this:
$("input[type='select']").change(function() {
$("input[type='text']").val(' '); });
Actually, you cant assign Null value to the form input. You can set it to be empty '' . But that wouldn't not be helpful in your case. The possible solution for you is to disable the field when 'No' is selected. Disabled input value would not be submitted in form. So the base case would be handled.
But if you are updating than you can handle it on the backend. You can add before filter.
before_filter: check_for_require_days
def check_for_require_days
params.merge!(require_days: nil) unless params[:require_days].present?
end
This would check if the value is disabled than it would not be in the form params so it would set it to null.
Just add :onchange => "$('#product_require_days').val('')" to your "require_booking" select
<%= f.select(:require_booking, get_advance_booking.collect {|p| [ p[:require_booking], p[:require_booking] ] }, {include_blank: false} , :class => 'form-control'), :onchange => "$('#product_require_days').val('')" %>

pass selected drop down value as params in rails link_to

I have a select tag which populates list of department names, When I select a value from drop down, I need to display an edit link below (link_to) and append the selected value of dropdown as id params.(I am not using form for this single select tag since I dont need to save value in my databse). How this could be possible. Please help. I am using rails2.3
I tried like the below but it didn't work.
Select A Dept
<%=select :select_dept, :dept, #dept.map{|dept| [dept.full_name, dept.id]},{:prompt => "#{t('select_a_batch')}"} %>
<%= link_to "Display", {:controller => "user", :action => "display_value", :id => $('#select_dept').val() } ,:class => "button" %>
Gopal is on the right track.
Give the link an id so you can pick it out
<%= link_to 'Display", {:controller ...}, :class => 'button', :id => 'display_link' %>
Hide it with CSS by default
#display_link { display:none; }
#display_link.showing { display:block; }
Then in javascript, do something like
$('#select_dept').on('change', function(ev) {
var deptId = $(this).find(':selected').val();
var newPath = '/users/' + deptId + '/display_value';
$('#display_link').attr('href', newPath);
$('#display_link').addClass('showing');
});
This will not set things up on page load, but you could run the same function you've passed as the change callback on page load to set things up (assuming one of the items might be selected on load).

How do I disable a submit button by default until it's text area has 1 character or more typed into it?

Currently when text area is focused on it expands it's height and the post and cancel button appear. Now I'd like to disable the submit button by default and only make it active once the text area has been typed into.
Later on I'll add opacity to the inactive submit button then take it away when the button is active just for a nice effect. But anyway I've tried applying disabled many ways and it doesn't work. I've tried various other things such as define a click function as well as submit then apply disabled using attr() to the disabled attribute of my form and it seems to have no effect.
HTML
<div class="comment_container">
<%= link_to image_tag(default_photo_for_commenter(comment), :class => "commenter_photo"), commenter(comment.user_id).username %>
<div class="commenter_content"> <div class="userNameFontStyle"><%= link_to commenter(comment.user_id).username.capitalize, commenter(comment.user_id).username %> - <%= simple_format h(comment.content) %> </div>
</div><div class="comment_post_time"> <%= time_ago_in_words(comment.created_at) %> ago. </div>
</div>
<% end %>
<% end %>
<% if logged_in? %>
<%= form_for #comment, :remote => true do |f| %>
<%= f.hidden_field :user_id, :value => current_user.id %>
<%= f.hidden_field :micropost_id, :value => m.id %>
<%= f.text_area :content, :placeholder => 'Post a comment...', :class => "comment_box", :rows => 0, :columns => 0 %>
<div class="commentButtons">
<%= f.submit 'Post it', :class => "commentButton" %>
<div class="cancelButton"> Cancel </div>
</div>
<% end %>
<% end %>
JQuery:
$(".microposts").on("focus", ".comment_box", function() {
this.rows = 7;
var $commentBox = $(this),
$form = $(this).parent(),
$cancelButton = $form.children(".commentButtons").children(".cancelButton");
// $commentButton = $form.children(".commentButtons").children(".commentButton");
$(this).removeClass("comment_box").addClass("comment_box_focused").autoResize();
$form.children(".commentButtons").addClass("displayButtons");
$cancelButton.click(function() {
$commentBox.removeClass("comment_box_focused").addClass("comment_box");
$form.children(".commentButtons").removeClass("displayButtons");
$commentBox.val("");
});
});
kind regards
Setting the disabled attribute doesn't work because if the disabled attribute is present, the field is disabled, regardless of the value of the attribute. You could use .removeAttr("disabled"), but it really makes the most sense to manipulate the disabled property which is more intuitive - it's just a boolean.
$commentButton.prop({ disabled: !$commentBox.val());
To be safe, bind to onkeyup, oninput, and onchange:
$commentBox.on("keyup input change", function () {
$commentButton.prop({ disabled: !$commentBox.val() });
});
If you need to manually enable or disable the button, such as after clearing the form, you can pass true or false directly to a call to .prop().
$commentButton.prop({ disabled: true });
Edit: Detailed breakdown
The .prop() method
The .prop() method gets and sets property values on elements, similar to how .attr() gets and sets attribute values on elements.
Considering this jQuery:
var myBtn = $("#myBtn");
myBtn.prop("disabled", true);
We can re-write that in plain JavaScript like this:
var myBtn = document.getElementById("myBtn");
myBtn.disabled = true;
Why we don't need an if statement
The reason we don't need an if statement is that the disabled property takes a boolean value. We could put a boolean expression in an if statement, and then depending on the result, assign a different boolean expression as the value of the property:
if (someValue == true) {
myObj.someProperty = false;
}
else {
myObj.someProperty = true;
}
The first problem is the redundancy in the if statement: if (someValue == true) can be shortened to if (someValue). Second, the whole block can be shortened to a single statement by using the logical not operator (!):
myObj.someProperty = !someValue;
The logical not operator (!) returns the negated result of an expression - ie true for "falsey" values, and false for "truthy" values. If you aren't familier with "truthy" and "falsey" values, here's a quick primer. Any time you use a non-boolean value where a boolean is expected, the value is coerced to boolean. Values that evaluate to true are said to be "truthy" and values that evaluate to false are said to be "falsey".
Type Falsey values Truthy values
———————— —————————————————— ——————————————————————
Number 0, NaN Any other number
String "" Any non-empty string
Object null, undefined Any non-null object
Since an empty string evaluates to false, we can get a boolean indicating whether there is any text in the textarea by applying ! to the value:
var isEmpty = !$commentBox.val();
Or, use !! to do a double negation and effectively coerce a string value to boolean:
var hasValue = !!$commentBox.val();
We could rewrite the jQuery from above to a more verbose form in plain JavaScript:
var myBtn = document.getElementById("myBtn");
var myTextBox = document.getElementById("myTextBox");
var text = myTextBox.value;
var isEmpty = !text;
if (isEmpty) {
myBtn.disabled = true;
}
else {
myBtn.disabled = false;
}
Or, a little shorter, and more similar to the original:
var myBtn = document.getElementById("myBtn");
var myTextBox = document.getElementById("myTextBox");
myBtn.disabled = !myTextBox.value;
You can try this:
var submit = $("input[type=submit]");
submit.attr("disabled","disabled");
$('textarea.comment_box').keyup(function() {
if ( !$(this).val() ) {
submit.attr("disabled","disabled");
} else {
submit.removeAttr("disabled");
}
});
Here's a JS Fiddle so that you can try this out: http://jsfiddle.net/leniel/a2BND/
You can first disable your submit button, and if textarea has a value enable it:
<form id="yourForm">
<textarea id="ta"></textarea>
<input id="submit" type="submit" disabled="disabled">
<form>
$("#yourForm").change(function() {
if ( $("#ta").val().length >= 1) {
$("#submit").removeAttr("disabled");
}
else {
$("input").attr("disabled", "disabled");
}
});
http://jsfiddle.net/dY8Bg/2/
You can achive this task using keyup event on text area. sample concept code below.
$("#textareaid").on('keyup', function (e) {
Count_Chars(this);
});
function Count_Chars(obj) {
var len = obj.value.length;
if (len >= 1) {
// do task
// enable post button
}
}
​
Added this to existing code to accomplish what I wanted. Marked answer that help me the most as winning answer and marked up others that helped.
commentButton = form.children(".commentButtons").children(".commentButton");
commentButton.attr("disabled","disabled");
commentBox.keyup(function() {
if ( !$(this).val() ) {
commentButton.attr("disabled","disabled");
} else {
commentButton.removeAttr("disabled");
}
});

How can I send an automatically generated ID for a form element to a javascript function?

I am trying to call a javascript function from my form page in a Rails 3 project. I need to send the function the ID of a particular element. Unfortunately I can't get the ID easily since it is automatically generated by a plugin.
I tried doing it this way:
<%= t.select :number_type, #id_types, {}, {:onchange => "has_other_field(' + the_value.id.to_s + "');"} %>
<% if (!the_value.nil?) && (!the_value.number_type.nil?) && !#id_types_sm.include? the_value.number_type) %>
<script type="text/javascript">
setup_other_field("<%= the_value.number_type %>", ###ID WOULD GO HERE###);
</script>
<% end %>
.. But since I don't know the ID of the element, I can't call it from the function.
So now I'm trying to do it this way, by calling the function from an "onload" when the input element loads:
<% if (!the_value.nil?) && (!the_value.number_type.nil?) && (!#id_types_sm.include? the_value.number_type) %>
<%# Call the function from the form helper only if the conditions are met %>
<%= t.select :number_type, #id_types, {}, {:onchange => "has_other_field(this.id);", :onload => "setup_other_field('" + the_value.number_type + "', this.id);"} %>
<% else %>
<%# Use the form helper without calling the function %>
<%= t.select :number_type, #id_types, {}, {:onchange => "has_other_field(this.id);"} %>
<% end %>
BUT I realize that onload does not work for this situation. Is there any workaround for this? How can I either
A) get the element ID from the field to the function in the first option, or
B) call this function from this input element whenever it loads?
... or C) an alternative way to do this?
Thanks in advance and let me know if more details would help.
If you have ID saved in the model, get it with <%= model.id %>
Exception to this rule is when you create object, and it is before it is written to database. If you go to edit or anywhere else it will be ok.
If you have it somewhere on the page :/ then you can use jQuery to get it for you.
< div id="id_of_the_element" attr_with_my_id="15" >ABC< /div >
$("#id_of_the_element").attr('attr_with_my_id')
< input id="id_of_the_element ... >< /input >
$("#id_of_the_element").value

How to validate an Ajax Form Submit (remote_form_tag)?

I have an ajax mail form like
- form_remote_tag :url=>mails_path,:condition=>"validate_mail()", :html => {:id=>"mailform",:method => :post, :class => 'ajax',:style=>"padding:15px;" } do |form|
.gimmespace
Naam
%br
= text_field_tag :name,params[:name],:class=>"title required"
.gimmespace
Telefoonnummber
%br
= text_field_tag :phone,params[:phone],:size=>25,:class=>"title"
.gimmespace
Mailadres
%br
= text_field_tag :email,params[:email],:size=>30,:class=>"title required"
.gimmespace
Onderwerp
%br
= text_field_tag :subject,params[:subject],:class=>"title required"
.gimmespace
Boodschap
%br
= text_area_tag :message,params[:message],:rows=>10,:cols=>45,:class=>"title required"
.gimmespace
= submit_tag "Verstuur",:id=>"mailsubmit",:class=>"sendBtn"
%button{:onclick=>"$.fn.colorbox.close();"} Annuleer
The above code is in HAML. It makes an ajax form submit to a controller. I have to validate the fields before it makes a submit. So, I tried several stuff. I read this article http://hillemania.wordpress.com/2006/09/18/rails-ajax-pre-submit-form-validation/ and made a before callback to a test javascript function to validate. Here is the javascript validating function.
function validate_mail() {
alert("Your Name, Email, Subject and Body Content are Required !");
return false;
}
As per the above function, it returns false any way and the form should not get submitted but, it submits well ajaxically. Is there any other way, please help.
I think you want to use the :condition option instead of the :before option. Something like this:
- form_remote_tag :url=> mails_path, :condition => "validate_mail()", ...
Then, if your condition function returns false, the form shouldn't be submitted.
Of course, you'll need to modify your validate_mail() function actually test that each form field isn't blank:
if ($('name').value == '' || $('phone').value == '' || ... ) {
alert('Something was blank...');
return false;
} else {
return true;
}
My Prototype syntax is rusty - that should get you on the right track though.

Categories

Resources