I am trying to figure out how to dynamically update a text input field when a user changes the option in one or two HTML select menus. I have included my code below showing how it currently works.
$('tickets').addEvent('change', function() {
if($('tickets').value > 0)
{
var cells = $$('.ticket2');
cells.each(function(cell) { cell.setAttribute('style','display:none;');});
var cells = $$('.ticket3');
cells.each(function(cell) { cell.setAttribute('style','display:none;');});
var sumValue = '$' + (100 * $('tickets').value + 10 * $('fiftytickets').value) + '.00';
$('ordertotal').value = sumValue;
$('ticket1heading').setHTML('Ticket(s)');
} else {
var cells = $$('.ticket2');
cells.each(function(cell) { cell.setAttribute('style','');});
var cells = $$('.ticket3');
cells.each(function(cell) { cell.setAttribute('style','');});
$('ticket2heading').setAttribute('style','text-align:center; font-weight:bold;');
$('ticket3heading').setAttribute('style','text-align:center; font-weight:bold;');
$('ordertotal').value = '$' + 250 + '.00';
$('ticket1heading').setHTML('Ticket 1');
}
});
The tickets select menu correctly affects the ordertotal text input field, but the fiftytickets select menu does not. I need the two to work independently of each other, but when each is changed, to affect the value of the ordertotal text input field.
Any assistance is greatly appreciated.
Thank you.
Mike
as said by JoDev, the select element's object is referenced with $('#tickets') and not just $('tickets').
also, I don't think that there is a value property in jquery for a select element.
you can get the value with the val() function.
Created a little fiddle for you here here
$('#tickets').change(function() {
$('#output').val($(this).val() + " - " + $('#fiftytickets').val());
});
$('#fiftytickets').change(function() {
$('#output').val($('#tickets').val() + " - " + $(this).val());
});
Related
I am trying to create several checkboxradio buttons groups in jQuery mobile that depend on a limit checkboxradio button group value. For example if a limit of 6 is selected I want to only allow the user to be able to select up to a total of 6 children based on all of the other checkboxradio button group selected values and disable everything else. When the limit changes I want to update the UI accordingly.
I have the following code in my change event handler whenever any of the checkboxradio buttons are clicks:
function updateUI(element) {
var limit = parseInt($('input[name="Limit_Total"]:checked').val(), 10);
// Children
var childCount = parseInt($('input[name="Child_Total"]:checked').val(), 10);
var secondChildCount = parseInt($('input[name="Second_Child_Total"]:checked').val(), 10);
var thirdChildCount = parseInt($('input[name="Third_Child_Total"]:checked').val(), 10);
var fourthChildCount = parseInt($('input[name="Fourth_Child_Total"]:checked').val(), 10);
var fifthChildCount = parseInt($('input[name="Fifth_Child_Total"]:checked').val(), 10);
// Totals
var totalChildern = childCount + secondChildCount + thirdChildCount + fourthChildCount + fifthChildCount;
// Enable the correct combination of children
$('input[name*="Child_Total"]').not(element).checkboxradio('disable').checkboxradio('refresh');
for (var i = 0; i <= 6; i++) {
if (i <= (limit - totalChildren)) {
$('input[id$="Child_Total_' + i + '"]').not(element).checkboxradio('enable').checkboxradio('refresh');
} else {
$('input[id$="Child_Total_' + i + '"]').not(element).attr('checked', false).checkboxradio('refresh');
}
}
}
I basically want to simulate the behavior illustrated in the image below:
The problem is it doesn't quite give me the behavior I want. It deselects all but the button I select within the group. I am trying to figure out the most efficient way to do this but I am having a hard time. Any suggestions or help would be greatly appreciated!
I have setup the following jsfiddle to demonstrate the UI: http://jsfiddle.net/X8swt/29/
I managed to solve my problem with the following function:
$('div fieldset').each(function() {
// Disable all none checked inputs
$(this).find('input:not(:checked)').checkboxradio().checkboxradio("disable").checkboxradio("refresh");
// Grab the selected input
var selectedElement = $(this).find('input:checked');
// Calculate the remaining children that can be selected
var remaining = (limit - totalChildern);
// Enable all inputs less than the selected input
$.each($(selectedElement).parent().prevAll().find('input'), function() {
$(this).checkboxradio().checkboxradio("enable").checkboxradio("refresh");
});
// Enable up to the remaining boxes past the selected input
$.each($(selectedElement).parent().nextAll().slice(0,remaining).find('input'), function() {
$(this).checkboxradio().checkboxradio("enable").checkboxradio("refresh");
});
});
Please feel free to comment or critique my solution.
Every time the client select an item from the autocomplete textbox, it automaticly appears in a div I created right under the textbox.
I would like to style with css each selected item that appears in the div, and not the whole div. For example, I want that every selected item will appear with a black border. (I could easily use css on the div, but then i'll get border for the whole div and not on each item selected).
That's the JS code. What i need is to add CSS to any new Selected country.
$(function() {
/* Textbox ID */ $("#destinations").autocomplete({
select: function (event, ui) {
/* div ID */ $("#DestinationsChosen").html(function(i, origText)
{
var SelectedCountry = ui.item.value.toString();
var CurrentText = origText.toString();
if ((CurrentText.indexOf(SelectedCountry) >= 0))
{
alert("Already Exists");
return CurrentText;
}
return CurrentText + " " + SelectedCountry;
})
}
});
})
Here is the whole code: http://jsfiddle.net/3zfcb04k/
Change this:
return CurrentText + " " + SelectedCountry;
to this:
return CurrentText + " <span>" + SelectedCountry + "</span><br/>";
Then apply the CSS on the span tag.
Here is the updated JSFiddle
try to put the css on the class="ui-menu-item"
.ui-menu-item{
color:red;
}
Using jquery and jquery mobile I try to make a dynamic form. Input fields are created or removed so that always one empty input field is left.
This is my jquery code to achieve this (try it here:
http://jsfiddle.net/SR864/17/):
$(document).ready(function() {
var total = 1;
// add new field
$("#bar").on("input", ".input", function() {
// add new field
if ($(".input").last().val() != "") {
var newFields = $(this).closest("p").clone();
newFields.find(":input").each(function() {
var name = $(this).attr('name').replace('-' + (total - 1), '-' + total);
var id = 'id_' + name;
$(this).attr({'name': name, 'id': id}).val('');
total++;
});
$(this).closest("p").after(newFields);
}
});
$("#bar").on("input", ".input", function() {
// remove empty field
if ($(this).val() == "") {
$(this).closest("p").remove();
}
});
});
I also would like to have "delete-buttons" inside of the input fields to remove the text from the input fields. jquery mobile provides data-clear-btn="true" for that. However, somehow the behavior of data-clear-btn="true" only works for the first input field - the new (cloned) ones don't get the clear button.
Question
How can I have the clear-buttons for the cloned input fields?
Bonus question
What is necessary to have input fields deleted when they are empty after the clear button is pressed?
jQM wraps input fields in a div ui-input-text. You need to clone input itself - not the wrapping div - change its' id, name, val()...etc. Then add it to form and enhance it using .textinput() function.
Moreover, you should wrap code in pagecreate event.
$(document).on("pagecreate", function () {
var counter = 0;
$("#bar").on("input", function (e) {
if ($(e.target).val().length === 1) { /* after 2 characters add a new input */
counter++;
var id = "input-" + counter;
var input = $(e.target).clone().prop({
id: id,
name: id
}).val("");
$(e.target).closest(".ui-input-text").after(input);
$("#" + id).textinput();
}
});
});
Demo
I had a check at the problem. By default the cross button (which is an tag) has a class 'ui-input-clear-hidden' which keeps it hidden till you type. Though you are cloning the element after you start typing, the duplicate element also has this class which keeps it hidden (may be cloning is done before the class 'ui-input-clear-hidden' is removed). So I suggest removing the class 'ui-input-clear-hidden' from your cloned object explicitely as shown below.
$("#bar").on("input", ".input", function() {
// add new field
if ($(".input").last().val() != "") {
var newFields = $(this).closest("p").clone();
newFields.find(":input").each(function() {
var name = $(this).attr('name').replace('-' + (total - 1), '-' + total);
var id = 'id_' + name;
$(this).attr({'name': name, 'id': id}).val('');
total++;
});
$(this).closest("p").after(newFields);
}
/* New line Added for Fix*/
newFields.find('a').removeClass('ui-input-clear-hidden');
});
The is(:focus) was the aproach. The final code is listed below:
setInterval(function(){
if($j("SELECT[name='cf20_field_7']").is(":focus")) return false;
var information = '';
var i = 1;
$j("#cf20_field_1").html();
//add new information to hidden field
$j("#cforms20form .info_for_email").each(function(){
var name = $j(this).find("INPUT[name='cf20_field_5']").val();
var inn = $j(this).find("INPUT[name='cf20_field_6']").val();
var view = $j(this).find("SELECT[name='cf20_field_7']").val();
//render
information += i + ")";
information += "Наименование организации: " + name + ".<br/>\n";
information += "Реквизиты организации: " + inn + ".<br/>\n";
information += "Стоимость заказа: выписка " + view + ".<br/>\n";
i++;
})
$j("#cf20_field_1").html(information);
hovered = true;
}
,100
);
Is there some possibility to fire function when there is no hover in SELECT field.
And also there may be aproach that to check is there is no hover on SELECT field.
It cause problemms. When you are trying to select another option cursor is begging while setInterval is working.
The best approach that i find is listed below:
//every 100 mil secconds update info
setInterval(function(){
$j("SELECT[name='cf20_field_7']").trigger('change');
if ( $j("SELECT[name='cf20_field_7']").on("change")) return false;
var information = '';
var i = 1;
$j("#cf20_field_1").html();
//add new information to hidden field
$j("#cforms20form .info_for_email").each(function(){
var name = $j(this).find("INPUT[name='cf20_field_5']").val();
var inn = $j(this).find("INPUT[name='cf20_field_6']").val();
var view = $j(this).find("SELECT[name='cf20_field_7']").attr("value");
//render
information += i + ")";
information += "Наименование организации: " + name + ".<br/>\n";
information += "Реквизиты организации: " + inn + ".<br/>\n";
information += "Стоимость заказа: выписка " + view + ".<br/>\n";
i++;
})
$j("#cf20_field_1").html(information);
}
,100
);
More information:
I can discribe situation more. So i had a form. onsubmit event didn`t work because there is another event is attachet. So i deside to update value of first field of form every 100 milisecs. The value is containing all dynamictly created "selects and inputs". But when i try to change value of the select by mouse. The function is fired and function check value of select and cause mouse begging. So i need somehow to check if that select is hovered to prevent firing of the function.
Invalid here:
if ( SELECT[name='cf20_field_7'].on("change"))
I guess you need this:
if ( $("SELECT[name='cf20_field_7']").on("change"))
But still, the above is invalid. You need some handler like:
$("SELECT[name='cf20_field_7']").on("change", function(){
return false;
});
if ($j("SELECT[name='cf20_field_7']").on("change")) return false
Not clear what should be checked here. I assume you want to run some function attached to onchange even of select. In that case you should use .trigger instead of .on. But in both cases return value will be jquery object (for chaining purposes) so basically your statement will always be true both with trigger and on If you want to test some value of select, you should do something like next:
if(someTestFunct($j("SELECT[name='cf20_field_7']"))) return false;
function someTestFunct(jObj) {
//some other code?
return jObj.val() == "some value to test";
}
Possibly some better approach may be used, but without more details it is hard to suggest something.
I have a JavaScript program that isn't properly functioning. For some reasons before it appends what it is actually getting from the checked radio box it appends three times with noting in the append except the styling. I'm not sure what I'm doing wrong.
$(document).delegate('#add-owner', 'pageinit', function () {
loadOwners();
$('#add-owner-save').bind('click', function () {
var permission = $('#editing-permissions option:selected').text();
var selection = $("input[type='radio']:checked") || [];
if (selection.length > 0) {
for (var i = 0; i < selection.length; i++) {
console.log($('#label-' + selection[i].id).find('.owner-name').text());
console.log($("input[type='radio']:checked").val());
$('.display-owners').append('<div class="ui-grid-a"><div class="ui-block-a">' + $('#label-' + selection[i].id).find('.owner-name').text() + '</div><div class="ui-block-b" style="text-align:right">' + permission + '</div></div>');
}
$('.display-owners').trigger('create');
}
$('.display-owners').show();
$('#add-owner').dialog('close');
$('input[name=contribute-radio]').attr('checked', false).checkboxradio("refresh");
return false;
});
});
I think the problem is that I have multiple radio areas on this page. How do I specify that I just want these radio buttons are the ones I want it to checked?
This code:
... + $('#label-' + selection[i].id).find('...
should be like this:
... + $('#label-' + selection[i].attr('id')).find('...
because what you have in selection array are jQuery objects, not DOM elements objects.
Thanks Esalija for pointing out my assumption was not correct.
Since said you have multiple sets of radio buttons, the selector you're using is finding all of them on the page so that is why you have multiple "checked" radio buttons.
This:
var selection = $("input[type='radio']:checked") || [];
To this:
var selection = $("input[name='radioset1']:checked") || [];
Then just name each radio set different and replace "radioset1" with the set you need for this one.