I'm trying to create a tool that allows users to generate CSS code. At the moment I'm working on input - when a user leaves a text input empty, I'd like a message to appear. The code I have at the moment doesn't seem to work in doing so, any ideas?
$("#btn-css").click(function() {
if( $('input').attr(value) = "" ) {
$('#output').append('All boxes must be completed');
} else {
$('.preview').attr('style', 'box-shadow: ' + $("#h-value").val() + 'px ' + $("#v-value").val() + 'px ' + $("#blur").val() + 'px ' + $("#spread").val() + 'px #' + $("#colour").val() + ';');
$('#output').append('box-shadow: ' + $("#h-value").val() + 'px ' + $("#v-value").val() + 'px ' + $("#blur").val() + 'px ' + $("#spread").val() + 'px #' + $("#colour").val() + ';');
}
});
How about this it will select all text inputs on the page then filter them to be the ones that are empty.
$("#btn-css").click(function() {
var emptyInputs = $('input:text').filter(function() { return this.value == ""; });
if (emptyInputs.length === 0) {
// Everything filled in
} else {
$('#output').append('All boxes must be completed');
}
});
You might also want to do:
var emptyInputs = $('input:text').filter(function() { return $.trim(this.value) == ""; });
This will also pick up text inputs with just whitespace.
use .val().. val() does the exact same thing you mentioned..
if( $('input').val() == "" ) {
to check for all input..
var inputVallength=$('input').filter(function(){
return this.value==""
}).length;
if(inputVallength == 0 || inputVallength < $('input').length){
$('#output').append('All boxes must be completed');
}
$('input').attr(value)
This selects ALL input elements on the entire page.
And also what #Mike Christensen said, you need at least 2 equal signs.
Just do
$(':input').each(function(){
if(!$(this).val()){
//logic
}
});
a Quick fiddle
Related
below is the js code for wikipedia search project. I am getting infinite for loop even though it had condition to stop repeating the loop. I am stuck in this problem.
$(document).ready(function() {
$('.enter').click(function() {
var srcv = $('#search').val(); //variable get the input value
//statement to check empty input
if (srcv == "") {
alert("enter something to search");
}
else {
$.getJSON('https://en.wikipedia.org/w/api.php?action=opensearch&search=' + srcv + '&format=json&limit=20&callback=?', function(json) {
$('.content').html("<p> <a href ='" + json[3][0] + "'target='_blank'>" + json[1][0] + "</a><br>" + json[2][0] + "</p>");
/*for loop to display the content of the json object*/
for (i = 1; i < 20; i++) {
$('p').append("<p><a href ='" + json[3][i] + "'target='_blank'>" + json[1][i] + "</a>" + json[2][i] + "</p>");
}
});
}
});
});
You are appending to each and every one of <p> in page.
Since your for loop appends even more <p> (and you possibly have a high number of <p> elements in your page beforehand) you overflow your call stack.
You probably wanted to append to a specific <p>. Try giving an id to your selector.
from what i can see in the url you need to do the following:
loop over the terms found and select the link based on the index of the element, chose a single element .contentto append the data not a set of elements p, this will increase the number of duplicated results
$.getJSON('https://en.wikipedia.org/w/api.php?action=opensearch&search='+srcv+'&format=json&limit=20&callback=?', function(json){
$.each(json[1],function(i,v){
$('.content').append("<p><a href ='"+json[2][i]+"'target='_blank'>"+json[0]+"</a>"+v+"</p>");
});
});
see demo: https://jsfiddle.net/x79zzp5a/
Try this
$(document).ready(function() {
$('.enter').click(function() {
var srcv = $('#search').val(); //variable get the input value
//statement to check empty input
if (srcv == "") {
alert("enter something to search");
}
else {
$.getJSON('https://en.wikipedia.org/w/api.php?action=opensearch&search=' + srcv + '&format=json&limit=20&callback=?', function(json) {
$('.content').html("<p> <a href ='" + json[3][0] + "'target='_blank'>" + json[1][0] + "</a><br>" + json[2][0] + "</p>");
/*for loop to display the content of the json object*/
var i = 1;
for (i; i < 20; i++) {
$('p').append("<p><a href ='" + json[3][i] + "'target='_blank'>" + json[1][i] + "</a>" + json[2][i] + "</p>");
}
});
}
});
});
Okay, that title will sound a bit crazy. I have an object, which I build from a bunch of inputs (from the user). I set them according to their value received, but sometimes they are not set at all, which makes them null. What I really want to do, it make an item generator for WoW. The items can have multiple attributes, which all look the same to the user. Here is my example:
+3 Agility
+5 Stamina
+10 Dodge
In theory, that should just grab my object's property name and key value, then output it in the same fashion. However, how do I setup that if-statement?
Here is what my current if-statement MADNESS looks like:
if(property == "agility") {
text = "+" + text + " Agility";
}
if(property == "stamina") {
text = "+" + text + " Stamina";
}
if(property == "dodge") {
text = "+" + text + " Dodge";
}
You get that point right? In WoW there are A TON of attributes, so it would suck that I would have to create an if-statement for each, because there are simply too many. It's basically repeating itself, but still using the property name all the way. Here is what my JSFiddle looks like: http://jsfiddle.net/pm2328hx/ so you can play with it yourself. Thanks!
EDIT: Oh by the way, what I want to do is something like this:
if(property == "agility" || property == "stamina" || ....) {
text = "+" + text + " " + THE_ABOVE_VARIABLE_WHICH_IS_TRUE;
}
Which is hacky as well. I definitely don't want that.
if(['agility','stamina','dodge'].indexOf(property) !== -1){
text = "+" + text + " " + property;
}
If you need the first letter capitalized :
if(['agility','stamina','dodge'].indexOf(property) !== -1){
text = "+" + text + " " + property.charAt(0).toUpperCase() + property.substr(1);
}
UPDATE per comment:
If you already have an array of all the attributes somewhere, use that instead
var myatts = [
'agility',
'stamina',
'dodge'
];
if(myatts.indexOf(property) !== -1){
text = "+" + text + " " + property.charAt(0).toUpperCase() + property.substr(1);
}
UPDATE per next comment:
If you already have an object with the attributes as keys, you can use Object.keys(), but be sure to also employ hasOwnProperty
var item = {};
item.attribute = {
agility:100,
stamina:200,
dodge:300
};
var property = "agility";
var text = "";
if(Object.keys(item.attribute).indexOf(property) !== -1){
if(item.attribute.hasOwnProperty(property)){
text = "+" + text + " " + property.charAt(0).toUpperCase() + property.substr(1);
}
}
Fiddle: http://jsfiddle.net/trex005/rk9j10bx/
UPDATE to answer intended question instead of asked question
How do I expand the following object into following string? Note: the attributes are dynamic.
Object:
var item = {};
item.attribute = {
agility:100,
stamina:200,
dodge:300
};
String:
+ 100 Agility + 200 Stamina + 300 Dodge
Answer:
var text = "";
for(var property in item.attribute){
if(item.attribute.hasOwnProperty(property)){
if(text.length > 0) text += " ";
text += "+ " + item.attribute[property] + " " + property.charAt(0).toUpperCase() + property.substr(1);
}
}
It's unclear how you're getting these values an storing them internally - but assuming you store them in a hash table:
properties = { stamina: 10,
agility: 45,
...
}
Then you could display it something like this:
var text = '';
for (var key in properties) {
// use hasOwnProperty to filter out keys from the Object.prototype
if (h.hasOwnProperty(k)) {
text = text + ' ' h[k] + ' ' + k + '<br/>';
}
}
After chat, code came out as follows:
var item = {};
item.name = "Thunderfury";
item.rarity = "legendary";
item.itemLevel = 80;
item.equip = "Binds when picked up";
item.unique = "Unique";
item.itemType = "Sword";
item.speed = 1.90;
item.slot = "One-handed";
item.damage = "36 - 68";
item.dps = 27.59;
item.attributes = {
agility:100,
stamina:200,
dodge:300
};
item.durability = 130;
item.chanceOnHit = "Blasts your enemy with lightning, dealing 209 Nature damage and then jumping to additional nearby enemies. Each jump reduces that victim's Nature resistance by 17. Affects 5 targets. Your primary target is also consumed by a cyclone, slowing its attack speed by 20% for 12 sec.";
item.levelRequirement = 60;
function build() {
box = $('<div id="box">'); //builds in memory
for (var key in item) {
if (item.hasOwnProperty(key)) {
if (key === 'attributes') {
for (var k in item.attributes) {
if (item.attributes.hasOwnProperty(k)) {
box.append('<span class="' + k + '">+' + item.attributes[k] + ' ' + k + '</span>');
}
}
} else {
box.append('<span id="' + key + '" class="' + item[key] + '">' + item[key] + '</span>');
}
}
}
$("#box").replaceWith(box);
}
build();
http://jsfiddle.net/gp0qfwfr/5/
So I have a form and you get the percent of the form you've completed. The problem is on one of the inputs, I get a result even though its empty. I'm not sure how to fix this. Heres the code
countMissing();
function countMissing() {
//Get total inputs
console.log("Total inputs " + form.getElementsByTagName('input').length);
//Divide by complete inputs out of 100% and get percent
console.log("The percentage is " + 100 / form.getElementsByTagName('input').length + "%");
var tot = 100 / form.getElementsByTagName('input').length + "%"
//Check
var cback=function(){
bad=0;
$('.form :text').each(function (i,e) {
if ($.trim($(e).val()) == "") bad++;
//Change width
$('.top').css('width', bad + '%');
});
//Missing amount of fields
if (bad > 0) $('.congrats').css("display", "block").text(100/bad + ' Completed ');
else $('.congrats').hide();
}
$(document).delegate('.form :text','focus',cback);
$(document).delegate('.form :text','keyup',cback);
}
And a link to the demo http://jsbin.com/xijemuli/2/edit Any ideas?
FIDDLE : http://jsfiddle.net/abdennour/3mH6w/3/
function count(){
console.log("Total inputs " + $('.form :text').length);
//Divide by complete inputs out of 100% and get percent
console.log("The percentage is " + bad / $('.form :text').length + "%");
return 100-(bad / $('.form :text').length)*100 + "%"
}
UPDATE :
Another example with form of 10 inputs : http://jsfiddle.net/abdennour/3mH6w/6/
I think you need to specify .value().length (not sure if it includes the brackets or not - from memory:
form.getElementsByTagName('input').value.length
There were several things going on with your code, but the primary problem you were having is calculating the percentage.
To find the percentage of form remaining, the math is:
(total_fields - empty_fields / total_fields)
After making that change (and a few others), your tested and working code is as follows:
countMissing();
function countMissing() {
var i = $('input').not('[type="button"]').length;
var cback=function(){
bad=0;
$('.form :text').each(function (i,e) {
if ($.trim($(e).val()) === "") bad++;
$('.top').css('width', bad + '%');
});
// Missing amount of fields
if (bad > 0) {
$('.congrats').css("display", "block").text(((i - bad)/ i) * 100 + ' Completed ');
} else {
$('.congrats').hide();
}
$(document).delegate('.form :text','focus',cback);
$(document).delegate('.form :text','keyup',cback);
}
I am pretty sure your code tried to kill my computer. Here is the approach I'd take:
$('form').on('input', function(e) {
var $inputs = $(this).find('input'),
$empties = $inputs.filter(function(){
return $.trim(this.value).length === 0;
});
$('.info').text($empties.length + ' of ' + $inputs.length + ' are empty!');
}).trigger('input');
along with a small demo: http://jsbin.com/gitef/4/edit?js,output
I have a label which displays the number of characters used in a textbox. When the page first loads it looks fine as it is small and in italics. I am using Bootstrap for that styling.
<label id="lblCharactersRemaining"><small><em>0 Out Of 255 Characters</em></small></label>
My JavaScript checks and updates the text in this label with the number of characters a user enters, this also works fine.
The problem is that each time the JS activates the styling goes back to the default MVC type. How can I make sure that when the JS executes that it doesn't remove the Bootstrap styling?
My JS is:
<script type="text/javascript">
var maximumLength = '#System.Configuration.ConfigurationManager.AppSettings["MaximumTextBoxLength"]';
if (document.getElementById("ObjectTextBox")) {
var txtbox = document.getElementById("ObjectTextBox");
txtbox.onkeyup = function () { IsMaxLength(this); };
}
function IsMaxLength(objTxtCtrl) {
if (objTxtCtrl.getAttribute && objTxtCtrl.value.length > maximumLength) {
objTxtCtrl.value = objTxtCtrl.value.substring(0, maximumLength);
}
if (document.all) {
document.getElementById('lblCharactersRemaining').innerText = (objTxtCtrl.value.length) + ' Out Of ' + maximumLength + ' Characters';
}
else {
document.getElementById('lblCharactersRemaining').textContent = (objTxtCtrl.value.length) + ' Out Of ' + maximumLength + ' Characters';
}
if (objTxtCtrl.value.length == 0) {
document.getElementById('lblCharactersRemaining').textContent = '0 Out Of ' + maximumLength;
}
}
</script>
Try :
function IsMaxLength(objTxtCtrl) {
if (objTxtCtrl.getAttribute && objTxtCtrl.value.length > maximumLength) {
objTxtCtrl.value = objTxtCtrl.value.substring(0, maximumLength);
}
if (document.all) {
$('#lblCharactersRemaining').html('<small><em>' + objTxtCtrl.value.length + ' Out Of ' + maximumLength + ' Characters</em></small>');
}
else {
$('#lblCharactersRemaining').html('<small><em>' + objTxtCtrl.value.length + ' Out Of ' + maximumLength + ' Characters</em></small>');
}
if (objTxtCtrl.value.length == 0) {
$('#lblCharactersRemaining').html('<small><em>0 Out Of ' + maximumLength + '</em></small>');
}
}
Every time you launch the function, it deleted the tags 'small' and 'em', so just add them...
UPDATE : PS : Using Jquery language...
UPDATE AFTER COMMENT :
BOOTPLY : http://bootply.com/106485
CODE :
JS :
$('button.jquery').on('click', function(){
$('#lblCharactersRemaining').html('<small><em>0 Out Of 85200</em></small>');
});
$('button.nojquery').on('click', function(){
document.getElementById('lblCharactersRemaining').innerHTML = '<small><em>0 Out Of 666</em></small>';
});
HTML :
<label id="lblCharactersRemaining"><small><em>0 Out Of 255 Characters</em></small></label>
<button class="jquery">Change label with jquery</button>
<button class="nojquery">Change label without jquery syntax</button>
The function is called via:
myChart.gChangeBarColour(1, "#000000");
This works:
// Changes bars colour
this.gChangeBarColour = function(gBarID, gBarColour) {
if (gBarID <= this.gData.length && gBarID >= 0) {
document.getElementById("gBar" + gBarID).style.backgroundColor = '#000000';
}
}
But this doesn't work:
// Changes bars colour
this.gChangeBarColour = function(gBarID, gBarColour) {
if (gBarID <= this.gData.length && gBarID >= 0) {
document.getElementById("gBar" + gBarID).style.backgroundColor = '" + gBarColour + "';
}
}
No errors in the console at all! Any ideas?
Your '" + gBarColour + "' is a string , delimited by single quotes ' that contains " + gBarColour + ", that value is then used as the color.
You need to leave out all the quotes and plus signs:
// assign the value of gBarColour to the backgroundColor property
document.getElementById("gBar" + gBarID).style.backgroundColor = gBarColour;
'" + gBarColour + "'
should be
gBarColour or ''+gBarColour