Page refreshes after javascript function - javascript

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.

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

how to get checked value from two url simultaneousl

I have two buttons one for Groups and second is for Skills. when i click on groups button one popup will show and in the popup the groups are showing with checkbox. wheni select the groups and click on save button the checked groups will show on the uper of group button and popup will close.and this same is for skills button also.
My problem is that when i select groups it will show on groups button but when i select skill i lost the selected groups.
right now i am doing this:
function OnClickButton () {
var display = "";
checkboxes = document.getElementsByName("group");
for( var i=0; i<checkboxes.length; i++){
if( checkboxes[i].checked ){
display += " " + checkboxes[i].value;
}
}
window.location.href='job_posting.html?data='+display;
}
<button type="button" onclick="OnClickButton()" >Save</button>
this is for Groups.
function OnClickButton1 () {
var display1 = "";
checkboxes = document.getElementsByName("skill");
for( var i=0; i<checkboxes.length; i++){
if( checkboxes[i].checked ){
display1 += " " + checkboxes[i].value;
}
}
window.location.href='job_posting.html?data='+display1;
}
<button type="button" onclick="OnClickButton1()" >Save</button>
And this is for skills.
I get the groups and skills in the url .Not for get the url i try this
function getUrlParameters(parameter, staticURL, decode){
var currLocation = (staticURL.length)? staticURL : window.location.search,
parArr = currLocation.split("?")[1].split("&"),
returnBool = true;
for(var i = 0; i < parArr.length; i++){
parr = parArr[i].split("=");
if(parr[0] == parameter){
return (decode) ? decodeURIComponent(parr[1]) : parr[1];
returnBool = true;
}else{
returnBool = "";
}
}
if(!returnBool) return false;
}
function get_data()
{
var idParameter = getUrlParameters("data","",true);
var idParameter1 = getUrlParameters("data1","",true);
document.getElementById('display').innerHTML=idParameter;
document.getElementById('display1').innerHTML=idParameter1;
}
Call this on
<body onLoad="get_data();">
Thank You in advance
Victor is right, that is the way I would do it too in raw JS, only with one difference:
<button type="button" onclick="OnNameSaveClicked()" >Save</button>
<button type="button" onclick="OnSkillSaveClicked()" >Save</button>
As you can see it does the same thing so you can do:
<button type="button" onclick="handleRedirect()" >Save</button>
And you would have the same effect with a fewer lines of code.
What you want to do is something similar to the following
function handleRedirect() {
var url = 'job_posting.html?data=';
var checkboxes = document.getElementsByName('name');
for(var i = 0; i < checkboxes.length; i++) {
if(checkboxes[i].checked){
url += checkboxes[i].value + " ";
}
}
url += '&data1=';
checkboxes = document.getElementsByName('skill');
for(var i = 0; i < checkboxes.length; i++) {
if(checkboxes[i].checked){
url += checkboxes[i].value + " ";
}
}
window.location.href = url;
}
<button type="button" onclick="handleRedirect()" >Save</button>
<button type="button" onclick="handleRedirect()" >Save</button>
Hope this helps!

Create form for function Html

This is my problem, hope get some support for this.
This is my function.
function show(n,q)
{
for(j=1;j<=n;j++)
{
s=j.toString().length;
t=0;
for(i=s-1;i>=0;i--)
{
t+=Math.pow((Math.floor(j/Math.pow(10,i))%10),q);
}
if(t==j){document.write(t+ " ");}
else{document.write("");}
}
}
show(1000,3);
With two inputs: number n and the exponent q it will solve all the numbers smaller than n which the sum of all the q-exponented of its digits is equal to itself.
For example: q=3, n=200, we have the number 153 because: 1^3 + 5^3 + 3^3 = 153
This function is OK, but due to my bad javascript skill, I dont know how to create a form alowing to enter n and q into 2 boxes, then click button "Show" we have results in the third box.
I have tried this below code, but it does not work :(
<input id='number' type='text' />
<input id='exp' type='text' />
<button onclick='javascript:show()'>Show</button>
<div id='res' style='width:100%;height:200px'></div>
<script>
function show() {
var n=document.getElementById('number').value,
var q=document.getElementById('exp').value,
out=document.getElementById('res'),
out.innerHTML="";
for(j=1;j<=n;j++)
{
s=j.toString().length;
t=0;
for(i=s-1;i>=0;i--)
{
t+=Math.pow((Math.floor(j/Math.pow(10,i))%10),q);
}
if(t==j){
out.innerHTML+=t+ " ";
}
else{
out.innerHTML+="";
}
}
}
</script>
In additon, I want to do it myself, could you guys tell me where i can find guide for this problem.
Thanks.
Your code has some punctuation issues.
Try to replace:
var n=document.getElementById('number').value,
var q=document.getElementById('exp').value,
out=document.getElementById('res'),
out.innerHTML="";
by
var n=document.getElementById('number').value,
q=document.getElementById('exp').value,
out=document.getElementById('res');
out.innerHTML="";
The code looks fine and will do what you are trying to do. Just there are some , (Comma) instead of ; (Semi-colon) in your code. Change them and then try.
Check the solution here.
http://jsfiddle.net/JszG2/
var n=document.getElementById('number').value;
var q=document.getElementById('exp').value;
out=document.getElementById('res');
Below is solution using JQuery....
<script>
function show() {
var num = parseInt($('#number').val());
var exp = parseInt($('#exp').val());
out = $('#res');
var num = document.getElementById('number').value;
var exp = document.getElementById('exp').value;
out = document.getElementById('res');
out.innerHTML = "";
for (p = 1; p <= num; p++) {
q = p.toString().length;
v = 0;
for (i = q - 1; i >= 0; i--) {
v = v+ Math.pow((Math.floor(p / Math.pow(10, i)) % 10), exp);
}
if (v == p) {
out.innerHTML += v + " ";
}
else {
out.innerHTML += "";
}
}
}
</script>

How to check< 2 and > 4 checkbox in javascript

I am trying to check the user input for greater than 2 and less than 4 checkbox selected.
I have to do this check before the form gets submitted.
Although I am using AlloyUI for client side validation. You can help me with vanilla javascript.
Please help me with my code...
<% for(loop here which generates more than one checkbox) { %>
<form name=".." method=".." action=".." onSubmit="return checkBox();">
<input type="checkbox" id=".." name=".."/>
</form>
%>
My javascript
function checkBox(){
alert("start");
var total = 0;
var max = form.checkcompare.length;
alert(max);
for(var idx = 0; idx < max; idx++)
{
if(eval("document.compareform.checkcompare[" + idx + "].checked") == true)
{
alert("checking");
total += 1;
}
}
if (total==2 || total==4)
{
/* document.compareform.submit(); */
alert("success");
}
else
{
alert('Select minimum of 2 or maximum of 4 Estimates');
}
//alert("You selected " + total + " boxes.");
}
Its not working..can someone help..Thanks
Something tells me you have little idea what you're doing.
First off, you're creating one form for EVERY checkbox. Open the form tag, then put in your loop to add the checkboxes, then close the form.
Now for your script...
form is undefined, so you can get its elements. form.checkcompare is undefined, so you can't get its length. You probably want to pass this in the onSubmit event (onSubmit="return checkBox(this);"), and function checkBox(form). Then use form.querySelectorAll('input[type=checkbox]');.
Next, why in the world are you using evil eval just to get an array index?
As if that weren't enough you say you want "between 2 and 4" but your code considers "3" invalid.
Finally, you're not returning anything.
Fixed (and improved) code:
function checkBox(form){
var total = 0;
var boxes = form.querySelectorAll('input[type=checkbox]:checked').length;
if (boxes < 2 || boxes > 4)
return true;
else {
alert('Select minimum of 2 or maximum of 4 Estimates');
return false;
}
}
function getNumberOfCheckedCheckboxes ( form ) {
var returnValue = 0;
var inputElements = form.getElementsByTagName("input");
for (var i = 0; i < inputElements.length; i ++) {
if (inputElements.type == "checkbox") {
if (inputElments.checked) {
returnValue ++;
}
}
}
return returnValue;
}

javascript setTimeout error

I'm trying to make a progress bar that moves each 5 seconds.
Here is my code:
function Progress(runner, validlinks)
{
if (runner <= validlinks)
{
var myString = document.getElementById('links').value;
var mySplit = myString.split("\n");
var ValidLinksCount = 0;
for(i = 0; i < mySplit.length; i++)
{
if (mySplit[i].search("who") != -1)
ValidLinksCount++;
ValidLinksCount++;
else if (mySplit[i].search("we") != -1)
ValidLinksCount++;
}
var jump = Math.ceil(100 / ValidLinksCount);
runner++;
document.getElementById("progressDiv").style.width = parseInt(document.getElementById("progressDiv").style.width) + jump + "%";
window.setTimeout(Progress(runner,ValidLinksCount), 5000);
}
}
I call it on button submit like this:
<input type="submit" name="submit" disabled="true" onclick="Progress(0,0);" value="check" />
It just runs and doesn't wait 5 seconds until next run, why? Thanks.
Pass, don't call, a function.
window.setTimeout(function() {
Progress(runner,ValidLinksCount);
}, 5000);

Categories

Resources