I am currently creating an application which consists of multiple HTML ranges.
<input id="r1" type="range" min="0" max="100" value="50" step="50" onChange="showValue(this.value)" />
On value change, the following function is called:
function showValue(newValue)
{
if (newValue == 100)
{
document.getElementById("range").innerHTML = "Calm";
mood = "Calm";
resetContent();
getContent(mood);
}
else if (newValue == 0)
{
document.getElementById("range").innerHTML = "Agitated";
resetContent();
mood = "Agitated";
getContent(mood);
}
else
{
document.getElementById("range").innerHTML = "";
resetContent();
}
}
getContent takes in the mood as a parameter and searches through an xml file and returns all results which match the mood:
function getContent(mood) {
$(xmlDoc).find("program").each(function(){
// this is where all the reading and writing will happe
if ($(this).find('mood').text() == mood) {
$("#content").append(
'<p>Name: ' + $(this).find('name').text() +
'<br> Mood: ' + $(this).find('mood').text() +
'</p>'
);
}
});
}
My aim is to create an aditional 3 ranges which hold different moods. How would I go about handling the different ranges within the showValue function so they all work independantly?
You can create an array in javascript to hold the mood's value
var moods=[["Agitated","Calm"],["sad","happy"],["angry","smiling"]];
function showValue(newValue,id) {
if (newValue == 100)
{
document.getElementById("range").innerHTML = moods[id][1];
mood = moods[id][1];
resetContent();
getContent(mood);
}
else if (newValue == 0)
{
document.getElementById("range").innerHTML = moods[id][0];
resetContent();
mood = moods[id][0];
getContent(mood);
}
else
{
document.getElementById("range").innerHTML = "";
resetContent();
}
}
Demo: https://jsfiddle.net/9y1foc5s/
What you are trying to do is make all the input use the same function but perform different actions basing on some of their attributes, in this case id:
function doIt($elem) {
if ($elem.attr('id') == 'r1') {
$("#output").html('action1' + $elem.val());
}
else if ($elem.attr('id') == 'r2') {
$("#output").html('action2' + $elem.val());
}
}
$('input').on('input', function(){
doIt($(this));
});
https://jsfiddle.net/xb51Lqnb/7/
Related
I am going to make more so just need help with how to make them different counters, i tired google and some html documents but didn't find the way to do it.
function clickCounter() {
if (typeof(Storage) !== "undefined") {
if (localStorage.clickcount) {
localStorage.clickcount = Number(localStorage.clickcount) + 1;
} else {
localStorage.clickcount = 1;
}
document.getElementById("result").innerHTML = "Sälj " + localStorage.clickcount + " st.";
} else {
document.getElementById("result").innerHTML = "Sorry, your browser does not support web storage...";
}
}
function clickCounter(b) {
if (typeof(Storage) !== "undefined") {
if (localStorage.clickcountr) {
localStorage.clickcountr = Number(localStorage.clickcountr) + 1;
} else {
localStorage.clickcountr = 2;
}
document.getElementById("resultr").innerHTML = "Annu " + localStorage.clickcountr + " st.";
} else {
document.getElementById("resultr").innerHTML = "Sorry, your browser does not support web storage...";
}
}
<p><button onclick="clickCounter()" type="button">Sälj!</button></p>
<div id="result"></div>
<p><button onclick="clickCounter(b)" type="button">Annu!</button></p>
<div id="resultr"></div>
--Sälj = first counter
--Annu = second counter
The problem is that you named your functions in the same way. Because of this, the second function overwrites the first one, and as result, both functions are calling the same function.
Usually you do not need to write two different functions that do the same thing. In your case, your JavaScript function should look something like this:
function clickCounter(id, label) {
var node = document.getElementById(id);
if (!node) {
return console.error('Element #' + id + ' not found');
}
if (window.localStorage === undefined) {
node.innerHTML = 'Sorry, your browser does not support web storage...';
} else {
var key = 'clickcount_' + id;
localStorage[key] = (++localStorage[key] || 1);
node.innerHTML = label + ' ' + localStorage[key] + ' st.';
}
}
And your buttons:
<p><button onclick="clickCounter('result', this.innerHTML)" type="button">Sälj!</button></p>
<div id="result"></div>
<p><button onclick="clickCounter('resultr', this.innerHTML)" type="button">Annu!</button></p>
<div id="resultr"></div>
I'm running a page which throws an error at the following line:
var label = $select.find('option:selected').html() || $select.find('option:first').html() || "";
For the sake of completeness, here is the full jQuery function (country-select.js):
(function($) {
$.fn.countrySelect = function (callback) {
$(this).each(function(){
var $select = $(this);
var lastID = $select.data('select-id'); // Tear down structure if Select needs to be rebuilt
if (lastID) {
$select.parent().find('span.caret').remove();
$select.parent().find('input').remove();
$select.unwrap();
$('ul#select-options-'+lastID).remove();
}
// If destroying the select, remove the selelct-id and reset it to it's uninitialized state.
if(callback === 'destroy') {
$select.data('select-id', null).removeClass('initialized');
return;
}
var uniqueID = Materialize.guid();
$select.data('select-id', uniqueID);
var wrapper = $('<div class="select-wrapper"></div>');
wrapper.addClass($select.attr('class'));
var options = $('<ul id="select-options-' + uniqueID +'" class="dropdown-content select-dropdown country-select"></ul>'),
selectChildren = $select.children('option, optgroup'),
valuesSelected = [],
optionsHover = false;
var label = $select.find('option:selected').html() || $select.find('option:first').html() || "";
// Function that renders and appends the option taking into
// account type and possible image icon.
var appendOptionWithIcon = function(select, option, type) {
// Add disabled attr if disabled
var disabledClass = (option.is(':disabled')) ? 'disabled ' : '';
var optgroupClass = (type === 'optgroup-option') ? 'optgroup-option ' : '';
var classes = option.attr('class');
var data = option.data('phone-code');
var opt = '<li class="' + disabledClass + optgroupClass + '"><span>';
if (option.val() !== '') {
opt += '<b class="flag flag-' + option.val().toLowerCase() + '"></b>';
}
opt += '<span class="option-label">' + option.html() + '</span>';
if (data && data !== '') {
opt += '<small>' + data + '</small>';
}
opt += '</span></li>';
options.append($(opt));
};
/* Create dropdown structure. */
if (selectChildren.length) {
selectChildren.each(function() {
if ($(this).is('option')) {
appendOptionWithIcon($select, $(this));
} else if ($(this).is('optgroup')) {
// Optgroup.
var selectOptions = $(this).children('option');
options.append($('<li class="optgroup"><span>' + $(this).attr('label') + '</span></li>'));
selectOptions.each(function() {
appendOptionWithIcon($select, $(this), 'optgroup-option');
});
}
});
}
options.find('li:not(.optgroup)').each(function (i) {
$(this).click(function (e) {
// Check if option element is disabled
if (!$(this).hasClass('disabled') && !$(this).hasClass('optgroup')) {
var selected = true;
options.find('li').removeClass('active');
$(this).toggleClass('active');
$newSelect.val($(this).find('.option-label').text());
activateOption(options, $(this));
$select.find('option').eq(i).prop('selected', selected);
// Trigger onchange() event
$select.trigger('change');
if (typeof callback !== 'undefined') callback();
}
e.stopPropagation();
});
});
// Wrap Elements
$select.wrap(wrapper);
// Add Select Display Element
var dropdownIcon = $('<span class="caret">▼</span>');
if ($select.is(':disabled'))
dropdownIcon.addClass('disabled');
// escape double quotes
var sanitizedLabelHtml = label.replace(/"/g, '"');
var $newSelect = $('<input type="text" class="select-dropdown" readonly="true" ' + (($select.is(':disabled')) ? 'disabled' : '') + ' data-activates="select-options-' + uniqueID +'" value="'+ sanitizedLabelHtml +'"/>');
$select.before($newSelect);
$newSelect.before(dropdownIcon);
$newSelect.after(options);
// Check if section element is disabled
if (!$select.is(':disabled')) {
$newSelect.data('constrainwidth', false)
$newSelect.dropdown({'hover': false, 'closeOnClick': false});
}
// Copy tabindex
if ($select.attr('tabindex')) {
$($newSelect[0]).attr('tabindex', $select.attr('tabindex'));
}
$select.addClass('initialized');
$newSelect.on({
'focus': function (){
if ($('ul.select-dropdown').not(options[0]).is(':visible')) {
$('input.select-dropdown').trigger('close');
}
if (!options.is(':visible')) {
$(this).trigger('open', ['focus']);
var label = $(this).val();
var selectedOption = options.find('li').filter(function() {
return $(this).find('.option-label').text().toLowerCase() === label.toLowerCase();
})[0];
activateOption(options, selectedOption);
}
},
'click': function (e){
e.stopPropagation();
}
});
$newSelect.on('blur', function() {
$(this).trigger('close');
options.find('li.selected').removeClass('selected');
});
options.hover(function() {
optionsHover = true;
}, function () {
optionsHover = false;
});
// Make option as selected and scroll to selected position
var activateOption = function(collection, newOption) {
if (newOption) {
collection.find('li.selected').removeClass('selected');
var option = $(newOption);
option.addClass('selected');
options.scrollTo(option);
}
};
// Allow user to search by typing
// this array is cleared after 1 second
var filterQuery = [],
onKeyDown = function(e){
// TAB - switch to another input
if(e.which == 9){
$newSelect.trigger('close');
return;
}
// ARROW DOWN WHEN SELECT IS CLOSED - open select options
if(e.which == 40 && !options.is(':visible')){
$newSelect.trigger('open');
return;
}
// ENTER WHEN SELECT IS CLOSED - submit form
if(e.which == 13 && !options.is(':visible')){
return;
}
e.preventDefault();
// CASE WHEN USER TYPE LETTERS
var letter = String.fromCharCode(e.which).toLowerCase(),
nonLetters = [9,13,27,38,40];
if (letter && (nonLetters.indexOf(e.which) === -1)) {
filterQuery.push(letter);
var string = filterQuery.join(''),
newOption = options.find('li').filter(function() {
return $(this).text().toLowerCase().indexOf(string) === 0;
})[0];
if (newOption) {
activateOption(options, newOption);
}
}
// ENTER - select option and close when select options are opened
if (e.which == 13) {
var activeOption = options.find('li.selected:not(.disabled)')[0];
if(activeOption){
$(activeOption).trigger('click');
$newSelect.trigger('close');
}
}
// ARROW DOWN - move to next not disabled option
if (e.which == 40) {
if (options.find('li.selected').length) {
newOption = options.find('li.selected').next('li:not(.disabled)')[0];
} else {
newOption = options.find('li:not(.disabled)')[0];
}
activateOption(options, newOption);
}
// ESC - close options
if (e.which == 27) {
$newSelect.trigger('close');
}
// ARROW UP - move to previous not disabled option
if (e.which == 38) {
newOption = options.find('li.selected').prev('li:not(.disabled)')[0];
if(newOption)
activateOption(options, newOption);
}
// Automaticaly clean filter query so user can search again by starting letters
setTimeout(function(){ filterQuery = []; }, 1000);
};
$newSelect.on('keydown', onKeyDown);
});
function toggleEntryFromArray(entriesArray, entryIndex, select) {
var index = entriesArray.indexOf(entryIndex),
notAdded = index === -1;
if (notAdded) {
entriesArray.push(entryIndex);
} else {
entriesArray.splice(index, 1);
}
select.siblings('ul.dropdown-content').find('li').eq(entryIndex).toggleClass('active');
// use notAdded instead of true (to detect if the option is selected or not)
select.find('option').eq(entryIndex).prop('selected', notAdded);
setValueToInput(entriesArray, select);
return notAdded;
}
function setValueToInput(entriesArray, select) {
var value = '';
for (var i = 0, count = entriesArray.length; i < count; i++) {
var text = select.find('option').eq(entriesArray[i]).text();
i === 0 ? value += text : value += ', ' + text;
}
if (value === '') {
value = select.find('option:disabled').eq(0).text();
}
select.siblings('input.select-dropdown').val(value);
}
};
$(function() {
$('.js-country-select').countrySelect();
});
$(document).on('change', '[data-country-select]', function() {
var target = 'select' + $(this).data('country-select');
var val = $(this).val();
var label = 'State';
var options = [
'<option value="" selected="" disabled="">Select State</option>'
];
if (val !== '') {
var country = window.__COUNTRIES[val];
var subdivisions = country.subdivisions;
var keys = Object.keys(subdivisions);
label = country.subdivisionName;
options = [
'<option value="" selected="" disabled="">Select ' + label + '</option>'
];
keys = keys.sort(function(a, b) {
var valA = subdivisions[a].toLowerCase();
var valB = subdivisions[b].toLowerCase();
if (valA < valB) return -1;
if (valA > valB) return 1;
return 0;
});
keys.forEach(function(key) {
options.push('<option value="' + key + '">' + subdivisions[key] + '</option>');
});
$(target).removeAttr('disabled');
} else {
$(target).attr('disabled', 'disabled');
}
$(target).parents('.input-field').find('label').html(label);
$(target).val('').html(options);
$(target).select2();
});
})(jQuery);
Here is the exception that I see in debug mode:
From what I understand from Failed to execute 'querySelectorAll' on 'Element' in ExtJS 5, :selected is not part of the CSS specification.
How should I fix this? Should I use:
var label = $select.find('option').filter(':selected').html() || $select.find('option').filter(':first').html() || "";
?
Converting Phil's comment to an answer, my debugger was set to pause on all exceptions (including caught ones). I had to de-activate the 'stop sign' button shown below to make the debugger work normally again.
I'm making some project like that should look like http://jsbin.com
when I'm trying to change the input width it is does'nt success
var clickedHtml = "#EFEDEF";
var clickedCss = "#EFEDEF";
var clickedJs = "#EFEDEF";
var clickedRes = "#EFEDEF";
function inputSize() {
var perc = 0;
if (clickedHtml == "#818081") {
perc++;
}
if (clickedCss == "#818081") {
perc++;
}
if (clickedJs == "#818081") {
perc++;
}
if (clickedRes == "#818081") {
perc++;
}
if (perc != 0) {
perc = 100 / perc;
}
return "\"" + perc.toString() + "%\"";
}
$("#htmlBut").click(function () {
if (clickedHtml == "#EFEDEF") {
$("#htmlBut").css("backgroundColor", "#818081");
clickedHtml = "#818081";
} else {
$("#htmlBut").css("backgroundColor", "#EFEDEF");
clickedHtml = "#EFEDEF";
}
$("#htmlField").css({
width: inputSize(),
display: 'block'
});
});
htmlField - input id.
htmlBut - html button id.
You need to just return the value as a string, no need to enclose it in ""
return perc.toString() + "%";
In your case the returned value "50%" is not valid, it should be just 50%
Return 'return perc.toString() + "%";' from inputSize method.
I want to move items between two Listboxes in ASP.Net using JQuery/Javascript and below is my code which is working perfectly.
function AddItems() {
var totalItemsSelected = 0;
var CurrentItems = 0;
var MessageLabel = document.getElementById('<%=lblITProgrammingMessage.ClientID%>');
var selectedOptions = jQuery('#<%=ListITProgramming.ClientID %> option:selected');
if (selectedOptions.length == 0) {
MessageLabel.innerHTML = "Please select skill(s) to add.";
jQuery('#<%= lblITProgrammingMessage.ClientID %>').fadeOut(2000, function () { MessageLabel.innerHTML = ""; });
jQuery('#<%= lblITProgrammingMessage.ClientID %>').fadeIn(500, function () { });
return false;
}
jQuery('select[name$=ListMyITProgramming] > option').each(function () { CurrentItems++; });
if (CurrentItems == 30) {
MessageLabel.innerHTML = "Maximum limit (30) is reached. You cannot add any more skills.";
jQuery('#<%= lblITProgrammingMessage.ClientID %>').fadeOut(2000, function () { MessageLabel.innerHTML = ""; });
jQuery('#<%= lblITProgrammingMessage.ClientID %>').fadeIn(500, function () { });
return false;
}
totalItemsSelected = CurrentItems + selectedOptions.length;
if (totalItemsSelected > 30) {
MessageLabel.innerHTML = "You can only select " + (30 - CurrentItems) + " item(s) more.";
jQuery('#<%= lblITProgrammingMessage.ClientID %>').fadeOut(2000, function () { MessageLabel.innerHTML = ""; });
jQuery('#<%= lblITProgrammingMessage.ClientID %>').fadeIn(500, function () { });
return false;
}
if (selectedOptions.length == 1) {
if (jQuery("#<%=ListMyITProgramming.ClientID %> option[value='" + selectedOptions.val() + "']").length > 0) {
}
else {
jQuery('#<%=ListMyITProgramming.ClientID %>').append(jQuery(selectedOptions).clone());
}
}
else if (selectedOptions.length > 1) { jQuery(selectedOptions).each(function () { if (jQuery("#<%=ListMyITProgramming.ClientID %> option[value='" + this.value + "']").length > 0) { } else { jQuery('#<%=ListMyITProgramming.ClientID %>').append(jQuery(this).clone()); } }); }
jQuery(selectedOptions).remove();
var hdn2 = "";
jQuery('select[name$=ListMyITProgramming] > option').each(function () { hdn2 += jQuery(this).attr('value') + ','; });
jQuery("#<%= listMyITProgrammingValues.ClientID %>").val(hdn2);
return false;
}
But this code is limited for only one set of ListBoxes as I have hard coded the ListBox names 'ListITProgramming' and 'ListMyITProgramming'.
Can anyone make this dynamic with two parameters in existing function?
Enclose the list control in an old-fashioned HTML tag with a known, hardcoded ID. Example:
<DIV id="List1Container">
<ASP:ListBox runat="server" id="list1"/>
</DIV>
In your Javascript, access the list control using the div's ID (List1Container) and jquery's ":first-child" selector. Ta da! You can now reference the list control without knowing its ID at all, so you don't have to do that messy code injection any more.
Bonus: Using this technique, you can now write fully static .js files, which means you can use minification and caching and greatly improve performance.
I have the following code:
function ViewModel() {
var self = this;
self.deckareax = ko.observable(0);
self.deckareay = ko.observable(0);
self.calculatedarea = ko.observable(20);
self.deckareax.subscribe(function () {
if (self.deckareax() == 0 || deckareay == 0) {
self.calculatedarea(0);
} else {
self.calculatedarea(self.deckareax() * self.deckareay());
}
}
);
self.deckareay.subscribe(function () {
console.log("deckareay " + self.deckareay())
if (self.deckareax() == 0 || self.deckareay() == 0) {
self.calculatedarea(0);
} else {
self.calculatedarea(self.deckareax() * self.deckareay());
}
}
);
self.deckareamxm = ko.computed({
read: function () {
return self.calculatedarea();
},
write: function (value) {
self.calculatedarea(value);
if ((self.deckareax() * self.deckareay(0)) != value) {
self.deckareax(0);
self.deckareay(0);
}
},
owner:self
});
}
;
ko.applyBindings(new ViewModel());
I want to be able to set the total area (deckareamxm) by either manually inputting or calcualting from entering deckareax * deckareay. If I enter a result and (deckareax * deckareay) doesn't equal total deck area x and y should be cleared.
This pretty much works however if I enter total area it clears both but also clears itself. If I then enter again total area it stays. I think it may have got to complex. Any ideas?
This jsfiddle seems to do what you want. There were a couple other bugs but I primary fixed the problem by moving the self.calculatedarea(value); to the bottom of the write function.