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.
Related
This is a simple quiz/questionnaire, that'll display results of the quiz on submission. It shows the results, but only for about half a second before resetting the page. I would also like for the page to show an alert if the user says they're under 18 when the quiz is submitted; it wouldn't keep them from seeing the answers, but just giving them a message.
function checkAge() {
if(age<18) {
alert("Always make sure you have adult supervision while caring for and handling any venomous arachnid.");
} }
function generateAnswers() {
var choice1score = 0;
var choice2score = 0;
var choice3score = 0;
var choice4score = 0;
}
var chosenAnswers = document.getElementsByTagName('result');
for (i=0; i<chosenAnswers.length; i++) {
if (chosenAnswers[i].checked) {
// add 1 to that choice's score
if (chosenAnswers[i].value == 'choice1') {
choice1score = choice1score + 1;
}
if (chosenAnswers[i].value == 'choice2') {
choice2score = choice2score + 1;
}
if (chosenAnswers[i].value == 'choice3') {
choice3score = choice3score + 1;
}
if (chosenAnswers[i].value == 'choice4') {
choice4score = choice4score + 1;
}
}
}
var maxscore = Math.max(choice1score,choice2score,choice3score,choice4score);
var resultBox = document.getElementById('result');
if (choice1score == maxscore) {
resultBox.innerHTML = "Asian Forest Scorpion"
}
if (choice2score == maxscore) {
resultBox.innerHTML = "Deathstalker Scorpion"
}
if (choice3score == maxscore) {
resultBox.innerHTML = "Desert Hairy Scorpion"
}
if (choice4score == maxscore) {
resultBox.innerHTML = "Emperor Scorpion"
}
}
This is where I put the code:
https://codepen.io/cryceks/pen/vjgzOZ
Use:
event.preventDefault();
This prevents the webpage from reloading and therefore clearing form data
i have a js search in my page that i don't get perfectly how does work because i don't know 100% js and jquery. As far as i think the code takes the input and search match with a link to a database that returns a JSON value depending on what name you put on the link (?name="the-input-name-here"), then, the code parse the json and determinates if the name of the input it's a valid surname and if it is the check if it has a running page, if it has redirects you to that page. If the input is a valid surname but doesn't have a running page it redirects you to "landing-page-yes.html". If the input isn't a valid surname it redirects you to "landing-page-no.html".
I need help to understand how the code does this in order to make a simplify version. How that call to another url database is parsed by the js ? How can i think something similar with a backend and ajax ? I need to understand 100% what this code does and i'm kinda lost.
THANKS !
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input id="srchid" width="100" onkeypress="submitonenter(document.getElementById('srchid').value, event, this)" />
<input onclick="nameCheck(document.getElementById('srchid').value);" value="CLICK HERE" type="button" style="background-color:#990033; color:#fff;border-style:outset;">
<div id="nameresults"></div>
<script >
<!--
Array.prototype.contains = function(obj) {
var i = this.length;
while (i--) {
if (this[i] === obj) {
return true;
}
} return false;
}
function cursor_wait() {
document.body.style.cursor = 'wait';
}
// Returns the cursor to the default pointer
function cursor_clear() {
document.body.style.cursor = 'default';
}
function nameCheck(sName) {
sName = trim(sName);
if(sName == ""){
alert("Please enter a name!");
return false;
}
cursor_wait();
routeToNameLookup(sName);
cursor_clear();
}
function $(id){return document.getElementById(id);}
// Get JSONP
function getJSON(url){
var s = document.createElement('script');
s.setAttribute('src',url);
document.getElementsByTagName('head')[0].appendChild(s);
}
function testcb(data){
//alert(data[0]);
}
function loaded(data) {
var name = document.getElementById('srchid').value;
var xmlhttp2;
//Using innerHTML just once to avoid multi reflow
$("nameresults").innerHTML = data[0];
if($("nameresults").innerHTML == 1){
if(data[1] == 1){
//display name page with content
var sNewName = name.replace (/'/g, ""); //remove any '
sNewName = removeSpaces(sNewName);
sNewName = convertNonAscii(sNewName);
//redirect to name crest
var sUrl = "http://www.heraldicjewelry.com/" + sNewName.toLowerCase() + "-crest-page.html";
//getJSON("http://www.gohapp.com/updatenamesearch.php?id=" + data[2] + "&pageurl=" + sUrl + "&callback=testcb");
//postwith(sUrl,{'pname':name});
window.location=sUrl;
} else {
//post to yes page
//postwith("http://www.heraldicjewelry.com/landing-page-yes.html",{'pname':name});
window.location="http://www.heraldicjewelry.com/landing-page-yes.html";
}
} else {
//post to no page
//postwith("http://www.heraldicjewelry.com/landing-page-no.html",{'pname':name});
window.location="http://www.heraldicjewelry.com/landing-page-no.html";
}
$("nameresults").innerHTML = "";
}
function routeToNameLookup(sSrchName) {
var name = document.getElementById('srchid').value;
if(sSrchName==""){
alert("Please enter your family name.");
} else {
var rn=Math.floor(Math.random()*1000000000000001)
getJSON("http://www.gohapp.com/namesearch_new.php?name="+name+"&rec=1&callback=loaded&rn="+rn);
}
}
function trim (sStr) {
var str = sStr.replace(/^\s+/, '');
for (var i = str.length - 1; i >= 0; i--) {
if (/\S/.test(str.charAt(i))) {
str = str.substring(0, i + 1);
break;
}
}
return str;
}
function postwith (to,p) {
var myForm = document.createElement("form");
myForm.method="post" ;
myForm.action = to ;
for (var k in p) {
var myInput = document.createElement("input") ;
myInput.setAttribute("name", k) ;
myInput.setAttribute("value", p[k]);
myForm.appendChild(myInput) ;
}
document.body.appendChild(myForm) ;
myForm.submit() ;
document.body.removeChild(myForm) ;
}
function removeSpaces(string) {
return string.split(' ').join('');
}
var PLAIN_ASCII =
"AaEeIiOoUu" // grave
+ "AaEeIiOoUuYy" // acute
+ "AaEeIiOoUuYy" // circumflex
+ "AaOoNn" // tilde
+ "AaEeIiOoUuYy" // umlaut
+ "Aa" // ring
+ "Cc" // cedilla
+ "OoUu" // double acute
;
var UNICODE =
"\u00C0\u00E0\u00C8\u00E8\u00CC\u00EC\u00D2\u00F2\u00D9\u00F9"
+ "\u00C1\u00E1\u00C9\u00E9\u00CD\u00ED\u00D3\u00F3\u00DA\u00FA\u00DD\u00FD"
+ "\u00C2\u00E2\u00CA\u00EA\u00CE\u00EE\u00D4\u00F4\u00DB\u00FB\u0176\u0177"
+ "\u00C3\u00E3\u00D5\u00F5\u00D1\u00F1"
+ "\u00C4\u00E4\u00CB\u00EB\u00CF\u00EF\u00D6\u00F6\u00DC\u00FC\u0178\u00FF"
+ "\u00C5\u00E5"
+ "\u00C7\u00E7"
+ "\u0150\u0151\u0170\u0171"
;
// remove accentued from a string and replace with ascii equivalent
function convertNonAscii(s) {
if (s == null)
return null;
var sb = '';
var n = s.length;
for (var i = 0; i < n; i++) {
var c = s.charAt(i);
var pos = UNICODE.indexOf(c);
if (pos > -1) {
sb += PLAIN_ASCII.charAt(pos);
} else {
sb += c;
}
}
return sb;
}
function submitonenter(name, evt,thisObj) {
evt = (evt) ? evt : ((window.event) ? window.event : "")
if (evt) {
// process event here
if ( evt.keyCode==13 || evt.which==13 ) {
thisObj.blur();
nameCheck(name);
//alert("looking for " + name);
}
}
}
//-->
</script>
The code below adds <font size="x">$text</font> to the WYSIWYG editor's textarea:
/**
* Set Size Context
*/
this.set_size_context = function(sizestate)
{
if (this.buttons['fontsize'])
{
if (typeof sizestate == 'undefined')
{
sizestate = this.editdoc.queryCommandValue('fontsize');
}
switch (sizestate)
{
case null:
case '':
{
if (is_moz)
{
sizestate = this.translate_fontsize(this.editdoc.body.style.fontSize);
}
}
break;
}
if (sizestate != this.sizestate)
{
this.sizestate = sizestate;
var i;
if (this.popupmode)
{
for (i in this.sizeoptions)
{
if (YAHOO.lang.hasOwnProperty(this.sizeoptions, i))
{
this.sizeoptions[i].style.display = (i == this.sizestate ? '' : 'none');
}
}
}
else
{
for (i = 0; i < this.buttons['fontsize'].options.length; i++)
{
if (this.buttons['fontsize'].options[i].value == this.sizestate)
{
this.buttons['fontsize'].selectedIndex = i;
break;
}
}
}
}
}
};
I replaced <font size tags with <span style="font-size tags in PHP side and everthing is working except the fontsize dropdown menu and the editor is still adding <font size when I choose a font size from the list. (it's correctly converted to <span style="font-size when the message is posted or previewed).
The question is, how the code above generates <font size tag and how can i replace it with <span style="font-size ?
Below are the other related sections to the fontsize in the JS:
this.build_fontsize_popup = function(obj, menu)
{
for (var n in sizeoptions)
{
if (YAHOO.lang.hasOwnProperty(sizeoptions, n))
{
var option = document.createElement('div');
option.innerHTML = '<span style="font-size:' + sizeoptions[n] + '">' + sizeoptions[n] + '</span>';
option.className = 'osize';
option.style.textAlign = 'center';
option.title = sizeoptions[n];
option.cmd = obj.cmd;
option.controlkey = obj.id;
option.editorid = this.editorid;
option.onmouseover = option.onmouseout = option.onmouseup = option.onmousedown = vB_Text_Editor_Events.prototype.menuoption_onmouseevent;
option.onclick = vB_Text_Editor_Events.prototype.formatting_option_onclick;
menu.appendChild(option);
}
}
}
and
this.translate_fontsize = function(csssize)
{
switch (csssize)
{
case '15px':
case '12px': return 1;
case '15px': return 2;
case '18px': return 3;
case '21px': return 4;
case '24px': return 5;
case '27px': return 6;
case '30px': return 7;
default: return '';
}
}
Here is the complete JS file: https://jsfiddle.net/07ttt9a7/
Wading though the full code, you need to fix the
case 'fontname':
{
this.wrap_tags('font', argument);
return;
}
to use 'span' instead of 'font'
or
modify the function beginning with
this.wrap_tags = function(tagname, useoption, selection)
{
I have a table that calculates a total depending on the input the user types. My problem is that the jquery code is calculating each key stroke and not "grabbing" the entire number once you stop typing. Code is below, any help woud be greatly appreciated.
$(document).ready(function() {
$('input.refreshButton').bind('click', EstimateTotal);
$('input.seatNumber').bind('keypress', EstimateTotal);
$('input.seatNumber').bind('change', EstimateTotal);
});
//$('input[type=submit]').live('click', function() {
function EstimateTotal(event) {
var tierSelected = $(this).attr('data-year');
var numberSeats = Math.floor($('#numberSeats_' + tierSelected).val());
$('.alertbox_error_' + tierSelected).hide();
if (isNaN(numberSeats) || numberSeats == 0) {
$('.alertbox_error_' + tierSelected).show();
} else {
$('.alertbox_error_' + tierSelected).hide();
var seatHigh = 0;
var seatLow = 0;
var seatBase = 0;
var yearTotal = 0;
var totalsArray = [];
var currentYear = 0;
$('.tier_' + tierSelected).each(function() {
seatLow = $(this).attr('data-seat_low');
firstSeatLow = $(this).attr('data-first_seat_low');
seatHigh = $(this).attr('data-seat_high');
seatBase = $(this).attr('data-base_cost');
costPerSeat = $(this).attr('data-cost_per_seat');
years = $(this).attr('data-year');
seats = 0;
if (years != currentYear) {
if (currentYear > 0) {
totalsArray[currentYear] = yearTotal;
}
currentYear = years;
yearTotal = 0;
}
if (numberSeats >= seatHigh) {
seats = Math.floor(seatHigh - seatLow + 1);
} else if (numberSeats >= seatLow) {
seats = Math.floor(numberSeats - seatLow + 1);
}
if (seats < 0) {
seats = 0;
}
yearTotal += Math.floor(costPerSeat) * Math.floor(seats) * Math.floor(years) + Math.floor(seatBase);
});
totalsArray[currentYear] = yearTotal;
totalsArray.forEach(function(item, key) {
if (item > 1000000) {
$('.totalCost_' + tierSelected + '[data-year="' + key + '"]').append('Contact Us');
} else {
$('.totalCost_' + tierSelected + '[data-year="' + key + '"]').append('$' + item);
}
});
}
}
You'll need a setTimeout, and a way to kill/reset it on the keypress.
I'd personally do something like this:
var calc_delay;
$(document).ready(function() {
$('input.refreshButton').bind('click', runEstimateTotal);
$('input.seatNumber').bind('keypress', runEstimateTotal);
$('input.seatNumber').bind('change', runEstimateTotal);
});
function runEstimateTotal(){
clearTimeout(calc_delay);
calc_delay = setTimeout(function(){ EstimateTotal(); }, 100);
}
function EstimateTotal() {
....
What this does is prompt the system to calculate 100ms after every keypress - unless another event is detected (i.e. runEstimateTotal is called), in which case the delay countdown resets.
I have this code, that checks some ids and enable others, the javascript is pretty clear about what it does, but since it corresponds to some specific id ranges, I cant do just a look until it finishes, but I'm looking a way to do this dynamic and save 40 lines of code (or more), since its not the best way.
function loopGroup1() {
var a = 0;
do {
$$('.selectedAuthorities-3_' + a).each(function(chk1) {
// watch for clicks
chk1.observe('click', function(evt) {
dynamicCheckbox1();
});
dynamicCheckbox1();
});
a++;
} while (a < 4);
}
function dynamicCheckbox1() {
// count how many of group_first are checked,
// doEnable true if any are checked
var doEnable = ($$('.selectedAuthorities-3_0:checked').length > 0) ? true
: false;
var doEnable1 = ($$('.selectedAuthorities-3_1:checked').length > 0) ? true
: false;
var doEnable2 = ($$('.selectedAuthorities-3_2:checked').length > 0) ? true
: false;
// for each in group_second, enable the checkbox, and
// remove the cssDisabled class from the parent label
var i = 0;
do {
$$('.selectedAuthorities-4_' + i).each(function(item) {
if (doEnable || doEnable1 || doEnable2) {
item.enable().up('li').removeClassName('cssDisabled');
} else {
item.disable().up('li').addClassName('cssDisabled');
}
});
i++;
} while (i < 4);
};
/*
*
* Loop Group 2
*
*
*/
function loopGroup2() {
var a = 0;
do {
$$('.selectedAuthorities-5_' + a).each(function(chk1) {
// watch for clicks
chk1.observe('click', function(evt) {
dynamicCheckbox2();
});
dynamicCheckbox2();
});
a++;
} while (a < 4);
}
function dynamicCheckbox2() {
// count how many of group_first are checked,
// doEnable true if any are checked
var doEnable3 = ($$('.selectedAuthorities-5_0:checked').length > 0) ? true
: false;
// for each in group_second, enable the checkbox, and
// remove the cssDisabled class from the parent label
var i = 0;
do {
$$('.selectedAuthorities-6_' + i).each(function(item) {
if (doEnable3) {
item.enable().up('li').removeClassName('cssDisabled');
} else {
item.disable().up('li').addClassName('cssDisabled');
}
});
i++;
} while (i < 4);
};
/*
*
* Loop Group 3
*
*
*/
function loopGroup3() {
var a = 0;
do {
$$('.selectedAuthorities-6_' + a).each(function(chk1) {
// watch for clicks
chk1.observe('click', function(evt) {
dynamicCheckbox3();
});
dynamicCheckbox3();
});
a++;
} while (a < 4);
}
function dynamicCheckbox3() {
// count how many of group_first are checked,
// doEnable true if any are checked
var doEnable4 = ($$('.selectedAuthorities-6_0:checked').length > 0) ? true
: false;
var doEnable5 = ($$('.selectedAuthorities-6_1:checked').length > 0) ? true
: false;
// for each in group_second, enable the checkbox, and
// remove the cssDisabled class from the parent label
var i = 0;
do {
$$('.selectedAuthorities-7_' + i).each(function(item) {
if (doEnable4 || doEnable5) {
item.enable().up('li').removeClassName('cssDisabled');
} else {
item.disable().up('li').addClassName('cssDisabled');
}
});
i++;
} while (i < 4);
};
/*
*
* Loop Group 4
*
*
*/
function loopGroup4() {
var a = 0;
do {
$$('.selectedAuthorities-9_' + a).each(function(chk1) {
// watch for clicks
chk1.observe('click', function(evt) {
dynamicCheckbox4();
});
dynamicCheckbox4();
});
a++;
} while (a < 4);
}
function dynamicCheckbox4() {
// count how many of group_first are checked,
// doEnable true if any are checked
var doEnable6 = ($$('.selectedAuthorities-9_0:checked').length > 0) ? true
: false;
var doEnable7 = ($$('.selectedAuthorities-9_1:checked').length > 0) ? true
: false;
// for each in group_second, enable the checkbox, and
// remove the cssDisabled class from the parent label
var i = 0;
do {
$$('.selectedAuthorities-10_' + i).each(function(item) {
if (doEnable6 || doEnable7) {
item.enable().up('li').removeClassName('cssDisabled');
} else {
item.disable().up('li').addClassName('cssDisabled');
}
});
i++;
} while (i < 4);
};
This isn't an answer, but there's some extra code in here:
var doEnable = ($$('.selectedAuthorities-3_0:checked').length > 0) ? true
: false;
should be
var doEnable = $$('.selectedAuthorities-3_0:checked').length > 0;
The ternary operator is just making it clumsier.