Using the same JQuery tokeninput box multiple times on a page - javascript

I am using Jquery TokenInput in my rails app to help users quickly input information. Each user has a profile with many items of the same class on it, call them college_items. Each college_item has its own edit link, which pops up a modal with the appropriate edit form for the modal.
I followed Ryan Bates's screencast and got TokenInput working properly using the following code:
In application.js:
$(function() {
$("#education_major_tokens").tokenInput("/majors.json", {
theme: "facebook"
})
});
In my view:
<%= f.text_field :major_tokens %>
In my model:
def major_tokens=(ids)
self.major_ids = ids.split(",")
end
The problem I'm running into is that this same field appears in each edit form, so in the edit form for the first item everything works perfectly, but in the edit form for any other item the javascript is not initialized. My question is how can I change the javascript to initialize each time this form element appears, not just the first?
EDIT:
I thought something like this might be the solution:
$(function() {
$("#education_major_tokens").each(function(){
$(this).tokenInput("/majors.json", {
theme: "facebook"
})
});
});
but it still isn't working for me. Anyone out there have any ideas?
EDIT 2:
Figured this out finally. See my edit above, only instead of using #education_major_tokens, I set each input to have :class => "major_input" and changed "#education_major_tokens" in the code to ".major_input"

I think this is a bit late, but try to assign a class to your token field
<input class="yourtokenfield" type="text" />
After that use this
$(function() {
$(".yourtokenfield").each(function(){
$(this).tokenInput("/majors.json", {
theme: "facebook"
})
});
});
I think your problem is due to improper name for class, and remember ID must only appear once in your HTML document.

Related

How to select form field by NAME complicate value

im using one web app where i can't edit html code, just can add js script.
And i need there to change some form fields. The issue is, they don't have any ID, only NAME values and they have extremely strange format.. And i don't know how can i select them with JS code..
This is form field i need to select
<input type="text" name="params[content][alias_translation][en-GB]" value="">
This is example of my code (works if NAME value is simple)
jQuery(function() {
jQuery("[name=something]").change(function() { ... });
});
This is what i try but this don't work
jQuery(function() {
jQuery("[name=params[content][alias_translation][en-GB]]").change(function() { ... });
});
Anyone please know how can i select this strange field?
Thanks a lot
Try to use quotes:
jQuery("[name='params[content][alias_translation][en-GB]']")

Select2 doesn't show options

I'm currently testing Select2.js in my ASP.NET MVC project.
The first test on a "normal" view just worked fine but now I'm trying to add this to a select box inside a partial view that gets loaded on Ajax Call and then displayed inside a <div> on the normal view page.
The code to generate the dropdown looks like this:
#Html.DropDownList("addRole",
new SelectList(ViewBag.availableRoles, "Id", "Name"),
"Rolle auswählen",
new { #name="addRole", #class = "form-control" }
)
And on the end of the partial view file I added the following:
$(document).ready(function () {
//var data = [{ id: 1, text: "Test" }];
$("#addRole").select2({
//data: data
});
});
It looks like it works because of the look of the select box changes but when I try to open it, it just shows nothing. Same happens when I uncomment the data variable code above.
It just doesn't show anything to me and I don't know why.
I've already tried to add the JavaScript code to $(document).ajaxComplete or in the success function from the AJAX call but it doesn't change anything.
I got the answer now.
The problem was not that the select2 element has no items, the problem was the given items did not show up. So I thought about why didn´t they show up and found out that I´m really stupid.
It did show up, but I can´t see it because of the z-index. My popup window got a z-index of 20k so the dropdown list was behind the window.
So to solve this just add:
.select2-dropdown {
z-index:99999;
}
Or add a dropdownCssClass to the select2 settings with the given z-index like this:
.select2-dropdown.increasezindex {
z-index:99999;
}
JS:
$(document).ready(function () {
$("#addRole").select2({
dropdownCssClass:'increasezindex'
});
});
In my case, I was displaying a select2 on a pop-up element and this causes the dropdown to disappear because it is attached by default to the <body> element.
Select2 troubleshooting guide highlights a similar issue with Bootstrap modals.
To overcome this problem I had to use the dropdown placement option provided,
let $select = $('select'),
$parent = $select.parent();
$select.select2({
dropdownParent: $parent
});

Special effect on parsley min check error message, Rails 4

I am creating simple app with registration, that consists of multiple field types - string, text, check-boxes etc.
I added parsley to display errors if any. That works great.
But now I want to change color for heading when error happens - specially when parsley-min-check triggers it.
My code:
<div class="col-lg-3">
Services
<hr>
<div class="services-heading"> (Minimum*3) </div>
<div class="services-reg">
<% #services.each do |service| %>
<li>
<%= check_box_tag 'service_ids[]', service.id, false, :'data-parsley-mincheck'=>3,:required => true%>
<%= h service.name%>
</li>
<% end %>
</div>
</div>
Now I am trying to trigger script when desired div (services-reg) consists of parsley error message.
$(document).ready(function() {
if ( $( ".services-reg > li.parsley-error").length ) {
$(".services-heading > p").css("color", "red");
}
});
but something isn't working as expected.
Console don't show any error message.
Thanks in advance for your time.
You are checking if .services-reg has an li.parsley-error on your document ready. At that moment, you haven't performed any validation.
You can probably take advantage of Parsley's events, such as parsley:form:error. So you can listen to that event, that is triggered when there's a validation error.
$(document).ready(function() {
// when there's a validation error
$.listen('parsley:form:error', function(ParsleyForm) {
$(".services-heading > p").css("color", "red");
});
});
Check this jsfiddle demo, where I'm also using parsley:form:success to remove the red color, when the form is correctly validated.
UPDATE: If you have groups of divs that contain a few fields and you want to change the color of the correct div, you can use the events parsley:field:error and parsley:field:success.
Example:
$.listen('parsley:field:error', function(ParsleyField) {
var pElement = ParsleyField.$element.parent('div').prev().find('p');
pElement.css("color", "red");
});
Here I'm finding the correct div based on the jQuery element for the input that has an error. You'll probably need to tweak this, based on the DOM of your form.
Take a look at this working jsfiddle.

Need help to target / modify custom data attribute

I am working on a website/webshop in WordPress with Woocommerce and tries to add a quantity field next to the 'add to cart' button.
I found this article/tutorial:
How to add quantity to product archives in WooCommerce (and keep ajax) - Christian Varga
http://christianvarga.com/how-to-add-quantity-to-product-archives-in-woocommerce-and-keep-ajax/
It got two small snippets - The first will work correct after copy/paste in my function.php file.
The second is some javascript code which will make the quantity field work together with the 'add to cart' button.
This is the code:
$('.input-text.qty', 'ul.products').on('change', function() {
$(this).closest('div').next('a').attr('data-quantity', $(this).val());
});
When I insert the javascript code nothing happens. It is because I use a custom theme (Avada) which has a different structure I guess.
This was also written on the tutorial:
*Note: This works with WooCommerce’s default HTML structure, but if you’re using a custom theme the HTML structure might be different, so
you’ll need to modify this script to suit.
Here is the link to my page:
http://frisk-matic.identitest.dk/kaffe/
I tried to target my 'add to cart' button but I cannot get it to work and I am not that skilled when it comes to Javascript.
Can someone help me? I would be so glad if I could get a little understanding how this code works.
I know that the first line is to select the quantity field we added and the products div and the result is to change the data-quantity attribute for the button.
Best regards
Samz3n
Try it like this
$('.input-text.qty').on('change', function() {
$(this).parent().next('a.add_to_cart_button').attr('data-quantity', $(this).val());
});
The problem is that your html markup is not the same with this template. I've inspected the markup and write some jQuery code. I think it will do the thing for you! :)
$('.quantity').find('input[type="number"]').on('change',function(){
$(this).parent().next('.product-buttons').find('.add_to_cart_button').data('quantity',$(this).val());
});
u might have some name collisions with your jQuery library, u can try this
var $ = jQuery;
$('.quantity').find('input[type="number"]').on('change', function () {
var value = $(this).val();
var button = $(this).parent().next('.product-buttons').find('.add_to_cart_button');
button.attr('data-quantity', value);
});
or better, use this until you fix naming collisions with jQuery
jQuery('.quantity').find('input[type="number"]').on('change', function () {
var value = jQuery(this).val();
var button = jQuery(this).parent().next('.product-buttons').find('.add_to_cart_button');
button.attr('data-quantity', value);
});

jQuery hide issue in register form

I'm not great with jQuery, so I'm having some trouble I can't bypass in a project.
I'm creating a register form with BuddyPress on this URL: http://medsimples.com/registrar/ (sorry for the portuguese, I'll guide you through).
In the last dropdown menu, I have the "Eu sou" (I am) field, which has "Paciente" (patient), "Médico" (physician) and "Estudante" (student) values.
Based on this, I'm using the following jQuery code to show/hide additional information on the form, if the users are physicians or students. The problem is, when we select Physician for example, all the form hides and the Medical div shows up. I don't want the whole form to hide and I don't know what is missed.
$(document).ready(function(){
$('#Estudante').hide();
$('#Medico').hide();
$("#field_5").change(function(){
$("#" + this.value).show().siblings().hide();
});
$("#field_5").change();
});
If someone can help me, I'd appreciate a lot. Thanks!
Try giving a common class to both the divs withe the id's Estudante and Medico like: class="additional-info"
Then you should try something like:
$(document).ready(function(){
$('.additional-info').hide();
$("#field_5").change(function(){
$('.additional-info').hide(); // Just in Case one of the 2 div's is showing
$("#" + $(this).val()).show();
});
});
Also you should be carefull at the select because the value for Medico has an additional string which is "(a)" so the Medico div is never selected.

Categories