help constructing while loop - javascript

Hi I am trying to create a while loop and I am having trouble with what to put in it so far I have:
function showSports(obj)
{
var groupId = obj.id.substring(0, 1);
var indx = obj.id.substring(obj.id.indexOf('_') + 1);
var id = indx.substring(0, indx.length + 1);
var displayInfo = false;
while (displayInfo)
{
if (indx == 1)
{
show('footballInfo');
hide('soccerInfo');
hide('baseballInfo');
}
if (indx == 2)
{
show('soccerdInfo');
hide('baseballInfo');
hide('footballInfo');
}
if (indx == 3)
{
show('baseballInfo');
hide('footballInfo');
hide('soccerdInfo');
}
displayInfo = true;
}
}
It is supposed to be able to loop through the links below and show/hide depending on which link is selected.
<a id='1link_1a' title="football Tab" onclick='showSports(this);'>
<span>FootBall</span>
</a>
<a id='1link_1b' title="soccer"
onclick='showSports(this); changeTab(this);'>
<span>Soccer</span>
</a>
<a id='1link_1c' title="baseball" onclick='showSports(this);'>
<span>Baseball</span>
</a>

I don't understand your use of the while statement. Perhaps you're thinking of a switch statement.
function showSports(obj)
{
var groupId = obj.id.substring(0, 1);
var indx = obj.id.substring(obj.id.indexOf('_') + 1);
var id = indx.substring(0, indx.length + 1);
switch (indx)
{
case 1:
show('footballInfo');
hide('soccerInfo');
hide('baseballInfo');
break;
case 2:
show('soccerdInfo');
hide('baseballInfo');
hide('footballInfo');
break;
case 3:
show('baseballInfo');
hide('footballInfo');
hide('soccerdInfo');
break;
}
}

RightSaidFred is correct, it sounds like you meant to use switch. One other point is that the line:
var id = indx.substring(0, indx.length + 1);
will have an index out of bounds error. I think you were thinking to do:
var id = indx.substring(0, indx.length - 1);

Related

Stop taking input in text-field (tag input)

I am taking some tags name like "study","reading" something like that in the textfield with the help of Bootstrap 4 Tag Input Plugin With jQuery - Tagsinput.js and I have also some predefine tags name contain by buttons. If I click the button then the count of the tag's will increase (count++) and again click this button count will decrease(count--). Same rules for the text-field tags and the total count of the tags in both fields (text and buttons)<=5.
I can count the total tags of the both field but can't stop taking input in text-field when it is greater than 5.
html
<button class="btnr btnr-tags-optional" id="1" onclick="tagSelect(this.id)" >1</button>
<button class="btnr btnr-tags-optional" id="2" onclick="tagSelect(this.id)" >2</button>
<button class="btnr btnr-tags-optional" id="3" onclick="tagSelect(this.id)" >3</button>
My Js
var tagsCount = 0;
var store = 0;
var total_tags = 0;
function tagSelect(clicked_id) {
if (total_tags < 5) {
var tags = document.getElementById(clicked_id);
if (tags.style.borderColor == "rgb(255, 72, 20)") {
tags.style.borderColor = "";
tagsCount--;
} else if (tags.style.borderColor == "") {
tags.style.borderColor = 'rgb(255, 72, 20)';
tagsCount++;
}
total_tags = store + tagsCount;
}
console.log(total_tags);
}
$('#tags_text').on('change', function() {
if (total_tags >= 5) {
$("#tags_text").attr('readonly');
console.log('condition')
} else {
$("#tags_text").removeAttr('readonly');
var items = $("#tags_text").tagsinput('items').length;
store = items;
total_tags = store + tagsCount;
console.log(total_tags);
}
});
Here is the example in jsfiddle
This problem is solved.
I have changed the maxTags value of the plugin with the change of the tags click.
window.tagsCount = 0;
var store = 0;
var total_tags = 0;
function tagSelect(clicked_id) {
var r = ("#" + clicked_id).toString();
if (total_tags < 5) {
if ($(r).hasClass("classActiveIssue")) {
$(r).removeClass("classActiveIssue");
window.tagsCount--;
} else {
$(r).addClass("classActiveIssue");
window.tagsCount++;
}
} else {
if ($(r).hasClass("classActiveIssue")) {
$(r).removeClass("classActiveIssue");
window.tagsCount--;
}
}
total_tags = store + tagsCount;
$("#optionsleft").text(total_tags + "/5 selected");
//console.log("total",total_tags);
}
$('#tags_text').on('change', function() {
var items = $("#tags_text").tagsinput('items').length;
store = items;
total_tags = store + tagsCount;
});
and add the line in add:
self.options.maxTags = 5 - window.tagsCount;
Here is the fiddle

Problem with add attr to img and set path

I have a little problem becouse I read values of labels and after that i want to set img src dependent on value label
Here some code and i see that is img attr don't add
getState generate divs with content
At the end is ajax call function where i get values from database and write them to the dynamically generated labels
The main problem now is then that don't read a values of labels correct becouse I got 3 labels with 3 diffrent states like "Active","Standby","Error" and it set for all Emergency Stop icon
function ChangeImage() {
let labels = $('label[data-id]');
$.each(labels, function (i, x) {
var states = $(x).text();
console.log(states);
if (states == "Active") {
var Active = "Images/kafle/zebatakActive.svg";
$(this).closest('img').attr("src", Active);
} else if (states == "Standby") {
var Standby = "Images/kafle/kafle_zebatka-01.svg"
$(this).closest('img').attr("src", Standby);
} else if (states == "Error") {
var error = "Images/kafle/kafle_zebatka-01.svg";
$(this).closest('img').attr("src", error);
} else if (states == "Setting") {
var Settings = "Images/kafel/kafle_zebatka-03.svg"
$(this).closest('img').attr("src", Settings);
} else {
var Emergency = "Images/kafle/kafle_status-yel-yel.svg";
$(this).closest('img').attr("src", Emergency);
}
});
}
function getState() {
try {
$.ajax({
type: "POST",
url: "Default.aspx/jsrequest",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
$("#ajax").empty();
$.each(data, function () {
$("#ajax").append('<div id="ajaxcontent"></div>');
$("#ajaxcontent").addClass("ajaxcontent");
$.each(this, function (k,v) {
$("#ajaxcontent").append('<div class="view">' + ' <label id="IdOfMachine">' + v.MachineId + '</label>'
+ '<label class="MachineState" name="Values" data-id= "' + v.MachineId + ' " > ' + v.CurrentStatus + '</label > '
+ '<img class="ChangeImg" data-id="' + v.MachineId + '"> ' + '</img > '
+ '<label id="MachineName">' + v.MachineName + '</label>' + '</div>');
});
});
},
error: function (response) {
alert("cos źle")
}
});
} catch (err) { }
}
public static List<StateOfMachine> jsrequest()
{
List<StateOfMachine> MachineState = new List<StateOfMachine>();
string DBInfo = #"Data Source=STACJA45;Initial Catalog=AutoRefresh;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False";
string sqlrequest = "Select MachineID,CurrentStatus,MachineName from MachineStates";
SqlConnection connection = new SqlConnection(DBInfo);
SqlCommand command = new SqlCommand(sqlrequest, connection);
connection.Open();
SqlDataReader DataReader = command.ExecuteReader();
while (DataReader.Read()) {
StateOfMachine machines = new StateOfMachine();
machines.MachineId = DataReader["MachineID"].ToString();
machines.MachineName = DataReader["MachineName"].ToString();
machines.CurrentStatus = DataReader["CurrentStatus"].ToString();
MachineState.Add(machines);
}
DataReader.Close();
command.Dispose();
connection.Close();
return MachineState;
}
first of all, welcome to StackOverflow :)
2 things in your code to avoid in the future:
DRY: Don't Repeat Yourself - every time you're writing the same thing over and over, you're doing it wrong :)
To be precise, always use === instead of == the later will give true for 1 == "1" and it's better to avoid it since the start.
Relating to your issue, apart for repeating yourself and the use of == you are specifying $(this) and that is ok as long as you pass a jQuery event because it's a self function, the object this is not what you are assuming.
your code could be changed to something as:
function ChangeImage() {
var labels = $('label[data-id]');
$.each(labels, function (i, x) {
var url = '';
var path = 'Images/kafle';
var state = $(x).text();
switch(state) {
case "Active": url = path + "/zebatakActive.svg"; break;
case "Standby": url = path + "/kafle_zebatka-01.svg"; break;
case "Error": url = path + "/kafle_zebatka-01.svg"; break;
case "Setting": url = path + "/kafle_zebatka-03.svg"; break;
default: url = path + "/kafle_status-yel-yel.svg"; break;
}
$('img[data-id="' + state + '"]').attr("src", url);
console.log({path, state, url});
});
}
code edited from comments
remove closet() and put find()
function ChangeImage() {
let labels = $('label[data-id]');
$.each(labels, function (i, x) {
var states = $(x).text();
switch(states)
{
case "Active":
$(this).find('img').attr("src","Images/kafle/zebatakActive.svg");
break;
case "Standby":
$(this).find('img').attr("src", "Images/kafle/kafle_zebatka-01.svg");
break;
case "Error":
$(this).find('img').attr("src", "Images/kafle/kafle_zebatka-01.svg");
break;
case "Setting":
$(this).find('img').attr("src", "Images/kafel/kafle_zebatka-03.svg");
break;
default:
$(this).find('img').attr("src", "Images/kafle/kafle_status-yel-yel.svg");
break;
}
});
}
SOLUTION:
If you are using HTML as in the following code snippet, you can use siblings([selector]) to read the matching sibling element and to change the src of the image.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
</head>
<body>
<div>
<img src="#" class="image" height="100" width="100">
<label data-id="1" class="image-link">Active</label>
</div>
<div>
<img src="#" class="image" height="100" width="100">
<label data-id="2" class="image-link">Emergency</label>
</div>
<button onclick="changeImage()">Change</button>
<script>
function changeImage() {
let labels = $('label[data-id]');
$.each(labels, function (i, x) {
var states = $(x).text();
if (states == "Active") {
var Active = "https://atlas-content-cdn.pixelsquid.com/stock-images/golden-soccer-ball-3yLR9z1-600.jpg";
$(this).siblings('img').attr( {"src": Active });
} else {
var Emergency = "https://upload.wikimedia.org/wikipedia/commons/4/47/PNG_transparency_demonstration_1.png";
$(this).siblings('img').attr("src", Emergency);
}
});
}
</script>
</body>
</html>

Display only three numbers of the total pagination numbers in Javascript

I'm trying to add some pagination numbers in Javascript. I already achieved the pagination, I also can show all the pagination numbers but I would like to show only three numbers from all the numbers. Let my show you what I achieved until now:
var values = [{name : "a"}, {name : "b"}, {name : "c"}, {name : "d"}, {name : "e"}, {name : "f"}, {name : "g"}, {name : "h"}, {name : "i"}, {name : "j"}];
var current_page = 1;
var records_per_page = 6;
if (values.length <= 6) {
btn_prev.style.display = "none";
btn_next.style.display = "none";
}
function prevPage() {
if (current_page > 1) {
current_page--;
changePage(current_page);
}
}
function nextPage() {
if (current_page < numPages()) {
current_page++;
changePage(current_page);
}
}
function changePage(page) {
var btn_next = document.getElementById("btn_next");
var btn_prev = document.getElementById("btn_prev");
var listing_table = document.getElementById("poi-cat-id");
var page_span = document.getElementById("page");
var pageNum = document.getElementById("pageNum");
// Validate page
if (page < 1) page = 1;
if (page > numPages()) page = numPages();
listing_table.innerHTML = "";
var href = getRootWebSitePath();
for (var i = (page - 1) * records_per_page; i < (page * records_per_page) && i < values.length; i++) {
var nametoslug1 = values[i].name;
var slug1 = convertToSlug(nametoslug1);
listing_table.innerHTML += '<div class="event-desc"><p>' + values[i].name + '</p></div>';
}
if (page == 1) {
btn_prev.style.color = "#404141";
} else {
btn_prev.style.visibility = "visible";
btn_prev.style.color = "#0c518a";
}
if (page == numPages()) {
btn_next.style.color = "#404141";
} else {
btn_next.style.visibility = "visible";
btn_next.style.color = "#0c518a";
}
male();
maen();
}
//this is where I add all the numbers of the pagination
var totnum = numPages();
for (var i = 0; i < numPages() + 2; i++) {
// We do not want page 0. You could have started with i = 1 too.
$('#page-num-container').append('' + (i + 1) + '');
}
======EDIT=====
function newPage(){
$('.pageClick').on('click', function (e) {
e.preventDefault();
changePage($(this).index() + 1);
});
} //when I click the number the pages won't change
function numPages() {
return Math.ceil(values.length / records_per_page);
}
window.onload = function () {
changePage(1);
};
and this is my html :
<div>
<ul class="content-full" id="poi-cat-id"></ul>
<div class="pagination-poi-arrows">
<div class="prev">
<img src="~/img/left-arrow-pagination.svg" />
</div>
<div class="page-num-container" id="page-num-container">
</div>
<div class="nex">
<img src="~/img/right-arrow-pagination.svg" />
</div>
</div>
<div class="pagination-poi-arrows" id="pager"></div>
</div>
Can anybody help would be highly appreciated since I've been stuck with this for a while.
If you want to show the adjacent page numbers, then you have to start iterating at i=current_page until i=current_page + 2.
However, it seems that in your code, you start counting at 1 with your pages. I advise you to start at 0.
Now, back to your code. You need to replace the loop with the following (if you're counting from 1):
function updatePagination(page) {
for (var i = page - 1; i < page + 1; i++) {
$('#page-num-container').append('<a href="javascript:pagesNr()"
class="pageClick">' + (i + 1) + '</a>');
}
}
// you need to clear the element before you update it
function clearPagination() {
$('#page-num-container').empty();
}
You would call both of these methods at the end of the changePage() method.

Page refreshes after javascript function

After I excecute my JS function over onClick button method. My site refreshes and everything that was writen with innerHTML is erased. I think i'm missing something. I will just put the whole JS function here. I probably don't understand something and that's what is causing it.
function stisk() {
var stevilo = prompt("Vnesi iskano stevilo");
var seznam = document.getElementById("vnos").value;
var pattern = new RegExp("^[0-9](,\s*[0-9])+$");
var vsota = 0;
var seznam = seznam.split(',');
var dolzina = seznam.length;
var pravilnost = pattern.test(seznam);
if (pravilnost == true) {
for (i = 0; i < dolzina; i++) {
vsota = vsota + parseInt(seznam[i]);
}
for (i = 0; i < dolzina - 1; i++) {
var star = document.getElementById("stevila").innerHTML;
if (isNaN(seznam[i]) == false) {
var starejsi = document.getElementById("stevila").innerHTML = star + parseInt(seznam[i]) + "+";
} else {
document.getElementById("stevila").innerHTML = "Vnos ni pravilen";
}
}
document.getElementById("stevila").innerHTML = starejsi + seznam[dolzina - 1] + "=" + vsota;
var c = 0;
for (i = 0; i < seznam.length; i++) {
if (stevilo == seznam[i]) {
c++;
}
}
if (c == 0) {
alert("stevila ni na seznamu");
} else {
alert("Stevilo je na seznamu");
}
} else {
document.getElementById("stevila").innerHTML = "Napacen vnos stevil";
}
}
HTML:
Here is the browser view:
After i press "V redu" (OK) Everything goes back to the start, expacting me to write a number inside. I want the 2+3+4=9 to stay there if that is possible? Thanks
Change:
<button onclick="stisk()">OK</button>
to:
<input type="button" onclick="stisk()">OK</input>
Like #Teemu said, < button > will submit a form element.
Another solution
<button onclick="stisk(event)">OK</button>
and in javascript
function stisk(e){
e.preventDefault();
...
This can be useful in other cases, like default behavior of <a href element is to redirect page, so you can prevent default behavior with event.preventDefault()
even better solution - let your button submit form, but prevent default on form submit
<form onsubmit="stisk(e)">
...
<button type="submit">
and in javascript
function stisk(e){
e.preventDefault();
...
and it will work when submitting form with Enter in input field.

How to update counter and replace text with button click

I have a form where people can add more input with a button.
The javascript function clones the "origin-item", but I can't seem to get the function to correctly update the value in #id_nested-TOTAL_FORMS and __prefix__ does not get replaced with a counter-number, It just copies and adds __prefix__ instead of 1 or 2 and so on.
Anyone know what is wrong with the function?
The script was found here: https://github.com/rotaris/dynamicformdjango/blob/master/todo/templates/edit_items_in_list.html
<input id="id_nested-TOTAL_FORMS" name="nested-TOTAL_FORMS" type="hidden" value="1">
<input id="id_nested-INITIAL_FORMS" name="nested-INITIAL_FORMS" type="hidden" value="0">
<input id="id_nested-MAX_NUM_FORMS" name="nested-MAX_NUM_FORMS" type="hidden" value="1000">
<div id="origin-item" class="hide item">
<div id="div_id_nested-__prefix__-name">
<label for="id_nested-__prefix__-name">Name</label>
<div class="controls col-lg-10">
<input id="id_nested-__prefix__-name" name="nested-__prefix__-name" type="text" />
</div>
</div>
<p><a id="add-new-item" href="#">Add new person</a></p>
<script type="text/javascript">
var prefix = 'nested';
var MAX_FORMS = '1000';
var MIN_FORMS = 1;
/*
* Perform any enhancements you'd like to a given item here
* e.g. add datepicker widgets, popovers etc.
*/
function enhanceItem(item) {
$('.btn.delete', item).popover({
offset: 10
});
}
function enhanceItems() {
$('.item').each(function() {
enhanceItem(this);
});
}
/*
* The opposite of enhanceItem()
*/
function diminishItem(item) {
$('.btn.delete', item).unbind();
}
function diminishItems() {
$('.item').each(function() {
diminishItem(this);
});
}
$(document).ready(function() {
enhanceItems();
});
function getFormCount() {
return parseInt($('#id_' + prefix + '-TOTAL_FORMS').val());
}
function updateFormCount(newValue) {
$('#id_' + prefix + '-TOTAL_FORMS').val(newValue);
}
/*
* ====================================================
* General Notes: 'Form' and 'Item' are used somewhat interchangeably.
* ====================================================
*/
$.fn.clearForm = function() {
return this.each(function() {
var type = this.type, tag = this.tagName.toLowerCase();
if (tag == 'form')
return $(':input',this).clearForm();
if (type == 'text' || type == 'password' || tag == 'textarea')
this.value = '';
else if (type == 'checkbox' || type == 'radio')
this.checked = false;
else if (tag == 'select')
this.selectedIndex = -1;
});
};
/*
* Given an element, this function replaces a given string/regex
* with another specified replacement (new_value) within the element
*/
function updateElement(el, target_regex, replacement) {
var id_regex = target_regex;
if ($(el).attr("for")) {
$(el).attr("for", $(el).attr("for").replace(id_regex, replacement));
}
if (el.id) {
el.id = el.id.replace(id_regex, replacement);
// Update the value of the hidden ID
// This hidden ID represents the ID of the model instance
var hidden_ID_patt = new RegExp('id_(' + prefix + '-\\d+)-id');
// Only update if an ID exists (i.e. if a corresponding model instance exists)
if (hidden_ID_patt.test(el.id)) {
$(el).val(new_value + 1);
}
}
if (el.name) {
el.name = el.name.replace(id_regex, replacement);
}
}
/*
* Given an element, this function replaces (the first?) occurence of a number
* that follows a specific prefix (e.g. 'exampleprefix-n')
* with another specified number (new_value) within the element
* where n is a number
*/
function updateElementIndex(el, prefix, new_value) {
var id_regex = new RegExp('(' + prefix + '-\\d+-)');
var replacement = prefix + '-' + new_value + '-';
updateElement(this, id_regex, replacement);
}
function reapplyEnhancements() {
// Apply some fresh enhancements
diminishItems();
enhanceItems();
}
/*
* btn = the button (or link or some source object) that instigated this action
* prefix = the prefix used in the formset (?)
*/
function addItem(btn, prefix) {
var formCount = getFormCount();
// You might like/want to do some validation before proceeding in this function
// i.e. before adding an item
// In this case, I'm limiting it to max number of forms
if (formCount < MAX_FORMS) {
// Clone a item (without event handlers) from the first item
//var item = $(".item:first").clone(false).get(0);
// Clone the origin item
var item = $("#origin-item").clone(false).get(0);
$(item).removeAttr("id");
$(item).removeClass("hide");
// Clear its values
$(':input', item).clearForm();
// Insert it after the last item
$(item).removeAttr('id').hide().insertAfter("form .item:last").slideDown(300);
$(':input, label', item).each(function() {
// Relabel/rename all the relevant bits
// '__prefix__' comes from #origin-item
// see 'empty_form': https://docs.djangoproject.com/en/1.4/topics/forms/formsets/#empty-form
var target_regex = new RegExp('(' + prefix + '-__prefix__-)');
var replacement = prefix + '-' + formCount + '-';
updateElement(this, target_regex, replacement);
// Remove error classes
$(this).removeClass("error");
});
reapplyEnhancements();
// Update the total form count (in the management form)
updateFormCount(formCount + 1);
}
else {
// Feel free to notify the user using some other technique instead of an JS alert
alert("Sorry, you can only have a maximum of " + MAX_FORMS + " goals.");
}
}
/*
* Relabel all items
*/
function relabelItems() {
var forms = $('.item'); // Get all the forms
// Update the total number of forms (likely 1 less than before)
$('#id_' + prefix + '-TOTAL_FORMS').val(forms.length);
var i = 0;
// Go through the forms and set their indices, names and IDs
for (formCount = forms.length; i < formCount; i++) {
$(":input, label", forms.get(i)).each(function() {
updateElementIndex(this, prefix, i);
});
}
}
/*
* Removes an item from a list of items
*/
function removeItem(btn, prefix) {
var formCount = getFormCount();
// Do some validation before proceeding
// In this case, just make sure there is at least one item
if (formCount > MIN_FORMS) {
var item = $(btn).parents('.item');
// Delete the item
$("*", item).fadeOut();
$(item).animate({'backgroundColor':'#fb6c6c'}, 300).slideUp('slow', function() {
$(item).remove();
relabelItems();
});
// Apply enhancements
enhanceItems();
}
else {
// Feel free to notify the user using some other technique instead of an JS alert
alert("Come on now, you need to have at least a minimum of " + MIN_FORMS + " item(s).");
}
}
// JavaScript to create a new items/entries
$(document).ready(function() {
$('#add-new-item').click(function(e) {
addItem(this, prefix);
return false;
});
$('a.delete').live("click", function(e) {
removeItem(this, prefix);
return false;
});
});
</script>
The bugs in this code seem to be caused by the variable named prefix being used for 2 different tasks.
Here it is used like this
$('#id_' + prefix + '-TOTAL_FORMS').val(newValue);
where I assume prefix is assigned '_prefix_', but later it is used like this
var target_regex = new RegExp('(' + prefix + '-__prefix__-)');
where I assume prefix is assigned 'id'
If you where to sort out the variable prefix to only contain one type of piece of information, by have 2 variables with different names.
I'm pretty sure everything would fall into place.

Categories

Resources