I've got a page wich is, basically, a list of divs; it doesn't matter how they're structured, suffice it to say that they're all visible by default. There are buttons on the page that lets you sort through them thanks to a java script. For example, if you click on the button "complete", the page shows only the divs containing the code
<div class="ended">complete</div>
while if you push on the "show all" button, it returns to show them all. (The structure is something like
<div class="entry">
<p>something</p>
<div class="ended">complete</div>
et cetera </div>
I've recently decided to add a new button, that picks a random div through them all. It all works well, except that when you try to show them all again after picking a random one, it doesn't work.
I'm not really all that familiar with JavaScript and JQuery (the random script I adapted from a script I found here), so I dont' understand what's wrong.
This is the code for (one of) the sorting script:
$('#completed').click(function() {
featureList.filter(function(item) {
if (item.values().ended == "complete") {
return true;
} else {
return false;
}
});
return false;
});
And this is the code for the "show all" button:
$('#filter-none').click(function() {
featureList.filter();
return false;
});
Finally, this is the code for the "random" button:
$(document).ready(function () {
$('#random').click(function () {
var E = document.getElementsByClassName("entry");
var m = E.length;
var n = parseInt(Math.random() * m);
for (var i = m - 1; i >= 0; i--) {
var e = E[i];
e.style.display = 'none';
}
E[n].style.display = '';
});
});
Hard to give an answer without knowing what's going on inside the .filter-function but based on what you've provided this could work:
$('#random').click(function () {
var entries = document.getElementsByClassName("entry");
var numEntries = entries.length;
var random = Math.floor(Math.random() * numEntries);
var counter = numEntries;
featureList.filter(function(item) {
counter--;
if (counter === random) {
return true;
} else {
return false;
}
});
return false;
}
I'm assuming the elements for which false is returned inside .filter are hidden somehow.
Since 'Show all' and 'Show only completed' is working, using the 'Show only completed'-way of hiding the wrong elements in 'Show random' should work.
Related
I have this section of javascript in my html that grabs a form input, puts it through a function and returns a json. I then want to either hide or show certain form elements based on the values in this json.
At the moment, i can do all of this fine except for changing the style.display properties of the elements im trying to hide/show, i can find them okay with getElementbyId (have tested this with other stuff) but the changes i make to the style don't seem to do anything.
As you can see below, i have put in a few alerts to make sure everything is working, and they all seem to align with what i need from the function. The alert showing style.display even matches up with what i'm trying to change it to, however even if it says "none", the form element still shows up.
<script type="text/javascript">
let selected = document.getElementById('selection1');
let optional_toggle = document.getElementById("optional_element");
let button = document.getElementById("button")
button.onclick = function() {
choice1 = selected.value;
fetch('/form_choice/' + choice1).then(function(response) {
response.json().then(function(data) {
if (data.show_optional === "True") {
optional_toggle.style.display = ""
window.alert("first part of if");
window.alert(optional_toggle.style.display);
window.alert(data.show_optional);
}
else {
optional_toggle.style.display = "none"
window.alert("second part of if");
window.alert(optional_toggle.style.display);
window.alert(data.show_optional);
console.log(optional_toggle);
}
}
)
}
)
}
</script>
Edit: i added the console.log lines in but nothing seems to show in the console.
console log image
The issue was that the page was reloading to it's original state after the script had been executed, so i stopped this by adding "; return false" after the function like so:
<script type="text/javascript">
let selected = document.getElementById('selection1');
let optional_toggle = document.getElementById("optional_element");
let button = document.getElementById("button")
button.onclick = function() {
choice1 = selected.value;
fetch('/form_choice/' + choice1).then(function(response) {
response.json().then(function(data) {
if (data.show_optional === "True") {
optional_toggle.style.display = ""
window.alert("first part of if");
window.alert(optional_toggle.style.display);
window.alert(data.show_optional);
}
else {
optional_toggle.style.display = "none"
window.alert("second part of if");
window.alert(optional_toggle.style.display);
window.alert(data.show_optional);
console.log(optional_toggle);
}
}
)
}
); return false
}
</script>
Im trying to prevent duplicated values on inputs with same name when I click a submit button, but it is not working and i am not sure why...
I need some help to understand why is not working?
Thanks lot in advance!
this is my code:
I tried with a solution I found here which it worked "on input change" behavior, but it doesnt with button click...
My button:
<button type="button" id="approve" class="positive valid" tabindex="-1">Approve</button>
and my jquery
$('#received').on('click',function() {
var $current = $(this);
if ($('input[name^="RE_SignedByID"]').val() == $current.val() && $('input[name^="RE_SignedByID"]').attr('tabindex') !== $current.attr('tabindex') ) {
alert('You can not have duplicated ID´s');
return false;
}else {
return true;
}
});
I want to show an alert and prevent the submit.
Thanks a lot for any help!
The issue is because you're comparing the value of the clicked button to the first input[name^="RE_SignedByID"] element.
To fix this you could instead create an array of all the input[name^="RE_SignedByID"] values using map(). You can then dedupe this list and compare the resulting array lengths. If they are different there was a duplicate. Try this:
$('#received').on('click', function(e) {
var values = $('input[name^="RE_SignedByID"]').map(function() {
return this.value.trim();
}).get();
var unique = [...new Set(values)];
if (values.length != unique.length) {
e.preventDefault();
alert('You can not have duplicated ID\'s');
}
});
Note that [...new Set(values)] will not work in IE. If you need to support legacy browsers there are plenty of alternatives to dedupe an array. See this answer for more information.
I could fix it! Here is the code... you can add a button event like:
$('#submit').on('click', function () {
var values = $('[name=RE_SignedByID]').map(function() {
return this.value.trim();
}).get();
var values2= $('[name=RE_OwnersID]').map(function() {
return this.value.trim();
}).get();
values.sort();
values2.sort();
for (var i = 0; i < values.length-1; i++) {
if( values[i] == values[i+1] && values[i] !=""){
showAlert(translator.getTranslation(' You can not have duplicated signers ID\'s'));
return false;
// break;
}
}
for (var i = 0; i < values2.length-1; i++) {
if( values2[i] == values2[i+1] && values2[i] !=""){
showAlert(translator.getTranslation(' You can not have duplicated owners ID\'s'));
return false;
// break;
}
}
});
I am trying make speed units toggle when clicking. However, this only works once. I have run out of things to try. I also tried .click(), .live(), .toggle() (which only made it disappear and reappear), etc.
HTML:
<li id="wind">Wind speed</br>
<p class='windSpeedKm'></p>
</li>
Javascript:
var click = true;
$('#wind').on('click', function() {
if (click = false) {
$('#wind').html(function() {
$(this).html("Wind speed<br>" + windKm);
click = true;
});
} else if (click = true) {
$('#wind').html(function() {
$(this).html("Wind speed<br>" + windMi);
click = false;
});
}
});
This isn't exactly what you asked for, but this will save you so much time it is unbelievable. It has an auto convert function built in so you don't have to manually update both numbers. It doesn't replace unnecessary to replace html.
<li id="wind">Wind speed</br>
<p class='windSpeedKm' km="500">500</p>
</li>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script>
function toMiles(km) {
return parseFloat(km) * 0.62137;
}
$('#wind').on('click', function() {
console.log($(this).attr("km"));
windSpeedKm = $(this).find(".windSpeedKm");
km = windSpeedKm.attr("km");
if (km === windSpeedKm.html()) {
windSpeedKm.html(toMiles(km));
} else {
windSpeedKm.html(km);
}
});
</script>
There are a few syntax issues with the code:
var click = true;
$('#wind').on('click', function() {
if (click) {
$(this).html("Wind speed<br>" + windKm):
click = true;
} else {
$(this).html("Wind speed<br>" + windMi);
click = false;
}
});
Note: there isn't any need to set click = true or click = false in your example as falling into the if statement by checking the click assignment value, this will already be true! You would only do this if you wanted to toggle the boolean to false after confirming it was true.
click = true should be click == true;
Would anyone know of a ready-made script or plugin providing:
-Shift click for check/uncheck all in range
-CTRL click to select or unselect all
That can works off the check inputs 'name' (instead of all on a page or all inside a div):
input[name='user_group[]']
input[name='record_group[]']
I've been using a couple of scripts (javascript and jQuery) but they're based on all checkboxes in a div or table and I'm not smart enough to roll my own or modify another script. Google searching on this has been a little difficult (too many common terms I think)...
Thanks Much Appreciated!
I started playing around with this script, although it's missing a CTRL+Click feature (select all/none control).
In it's original form it works against all checkboxes on a page. I changed the "$('input[type=checkbox]').shiftClick();" linke to "$("input[name='selected_employees[]']").shiftClick();" and as far as I can tell it seems to be working perfectly now against only the single checkbox group.
The only flaw (for my requirements) is there is not a CTRL+Click function to toggle check or un-check all checkboxes in the group.
<script type="text/javascript">
$(document).ready(function() {
// shiftclick: http://sneeu.com/projects/shiftclick/
// This will create a ShiftClick set of all the checkboxes on a page.
$(function() {
$("input[name='selected_employees[]']").shiftClick();
// $('input[type=checkbox]').shiftClick();
});
(function($) {
$.fn.shiftClick = function() {
var lastSelected;
var checkBoxes = $(this);
this.each(function() {
$(this).click(function(ev) {
if (ev.shiftKey) {
var last = checkBoxes.index(lastSelected);
var first = checkBoxes.index(this);
var start = Math.min(first, last);
var end = Math.max(first, last);
var chk = lastSelected.checked;
for (var i = start; i < end; i++) {
checkBoxes[i].checked = chk;
}
} else {
lastSelected = this;
}
})
});
};
})(jQuery);
});
</script>
I believe this should work!
Working demo on jsFiddle: http://jsfiddle.net/SXdVs/3/
var firstIndex = null;
$(":checkbox").click(function(e) {
$this = $(this);
if (e.ctrlKey) {
if ($this.is(":checked")) {
$("input[name='"+ $this.attr("name") +"']").attr("checked", "checked");
} else {
$("input[name='"+ $this.attr("name") +"']").removeAttr("checked");
}
} else if (e.shiftKey) {
$items = $("input[name='"+ $this.attr("name") +"']");
if (firstIndex == null) {
firstIndex = $items.index($this);
} else {
var currentIndex = $items.index($this);
var high = Math.max(firstIndex,currentIndex);
var low = Math.min(firstIndex,currentIndex);
if ($this.is(":checked")) {
$items.filter(":gt("+ low +"):lt("+ high +")").attr("checked", "checked");
} else {
$items.filter(":gt("+ low +"):lt("+ high +")").removeAttr("checked");
}
firstIndex = null;
}
}
});
I have the following snippets of code. Basically what I'm trying to do is in the 1st click function I loop through my cached JSON data and display any values that exist for that id. In the 2nd change function I capturing whenever one of the elements changes values (i.e. yes to no and vice versa).
These elements are all generated dynamically though the JSON data I'm receiving from a webservice. From my understanding that is why I have to use the .live functionality.
In Firefox everything works as expected (of course). However, in IE7 it does not. In IE7, if I select a radio button that displays an alert from the click function then it also adds to the array for the changed function. However, if the radio button does not do anything from the click function then the array is not added to for the change.
As I look at this code I'm thinking that I might be able to combine these 2 functions together however, right now I just want it to work in IE7.
$(document).ready(function () {
//This function is run whenever a 'radio button' is selected.
//It then goes into the CPItemMetaInfoList in the cached JSON data
//($.myglobals) and checks to see if there are currently any
//scripts to display.
$("input:radio").live("click", function () {
var index = parseInt(this.name.split(':')[0]);
for (i = 0; i <= $.myglobals.result.length - 1; i++) {
if ($.myglobals.result[i].CPItemMetaInfoList.length > 0) {
for (j = 0; j <= $.myglobals.result[i].CPItemMetaInfoList.length - 1; j++) {
if (index == $.myglobals.result[i].QuestionId) {
alert($.myglobals.result[i].CPItemMetaInfoList[j].KeyStringValue);
return;
}
}
}
}
});
});
$(document).ready(function () {
var blnCheck = false;
//Checks to see if values have changed.
//If a value has been changed then the isDirty array gets populated.
//This array is used when the questionSubmit button is clickeds
$('input').live('change', function () {
blnCheck = false;
for (i = 0; i <= isDirty.length - 1; i++) {
if (isDirty[i] == $(this).attr("name")) {
blnCheck = true;
break
}
}
if (blnCheck == false) {
isDirty[arrayCount] = $(this).attr("name");
arrayCount += 1;
alert($(this).attr("name"));
}
});
$('textarea').live('change', function () {
blnCheck = false;
for (i = 0; i <= isDirty.length - 1; i++) {
if (isDirty[i] == $(this).attr("id")) {
blnCheck = true;
break
}
}
if (blnCheck == false) {
isDirty[arrayCount] = $(this).attr("id");
arrayCount += 1;
//alert($(this).attr("name"));
}
});
});
UPDATE:
I had to move this chunk of code into the click function:
blnCheck = false;
for (i = 0; i <= isDirty.length - 1; i++) {
if (isDirty[i] == $(this).attr("name")) {
blnCheck = true;
break
}
}
if (blnCheck == false) {
isDirty[arrayCount] = $(this).attr("name");
arrayCount += 1;
alert($(this).attr("name"));
}
Like this:
$(document).ready(function () {
//This function is run whenever a 'radio button' is selected.
//It then goes into the CPItemMetaInfoList in the cached JSON data
//($.myglobals) and checks to see if there are currently any
//scripts to display.
$("input:radio").live("click", function () {
var index = parseInt(this.name.split(':')[0]);
for (i = 0; i <= $.myglobals.result.length - 1; i++) {
if ($.myglobals.result[i].CPItemMetaInfoList.length > 0) {
for (j = 0; j <= $.myglobals.result[i].CPItemMetaInfoList.length - 1; j++) {
if (index == $.myglobals.result[i].QuestionId) {
alert($.myglobals.result[i].CPItemMetaInfoList[j].KeyStringValue);
return;
}
}
}
}
blnCheck = false;
for (i = 0; i <= isDirty.length - 1; i++) {
if (isDirty[i] == $(this).attr("name")) {
blnCheck = true;
break
}
}
if (blnCheck == false) {
isDirty[arrayCount] = $(this).attr("name");
arrayCount += 1;
}
});
});
But...
I had to leave the change function the same. From my testing I found that the .click function worked for IE7 for the radio buttons and checkbox elements, but the .change functionality worked for the textboxes and textareas in IE7 and FF as well as the original functionality of the radio buttons and checkbox elements.
This one got real messy. Thanks to #Patricia for looking at it. Here suggestions did lead me to this solution. I'm going to leave the question unanswered as I wonder if there isn't a cleaner solution to this.
Fact: change event on radio buttons and checkboxes only get fired when the focus is lost (i.e. when the blur event is about to occur). To achieve the "expected" behaviour, you really want to hook on the click event instead.
You basically want to change
$('input').live('change', function() {
// Code.
});
to
$('input:radio').live('click', functionName);
$('input:not(:radio)').live('change', functionName);
function functionName() {
// Code.
}
(I'd however also take checkboxes into account using :checkbox selector for the case that you have any in your form, you'd like to treat them equally as radiobuttons)
I think this is because IE fires the change when focus is lost on checks and radios. so if the alert is popping up, focus is being lost and therefor the change event is firing.
EDIT:
try changing the $('input') selector to $('input:not(:radio)')
so the click will fire for your radios and the change for all your others.
Edit #2:
How bout putting the stuff that happens on change into a separate function. with the index as a parameter. then you can call that function from the change() and the click(). put the call to that function after your done with the click stuff.
You're declaring your blnCheck variable inside one of your document.ready() functions. You don't need two of these either, it could all be in one.
This means that the variable that you're declaring there won't be the one used when your change function is actually called, instead you're going to get some kind of implicit global. Don't know if this is part of it, but might be worth looking at. You should declare this at the top of your JS file instead.