Jquery increment numbers with a limit of 5 - javascript

I'm adding text fields with a onclick. What I'm trying to do is limit the amount of boxes to about 5.
I also need to increment the number to use as an ID.
my code:
jQuery('#add_slider_image').click(function() {
var i = 0
var plus = ++i;
jQuery('.form-table').append("<tr><td><input type'text' value='' name='slider[]' /><input type='button' name='sliderbut' value='Upload' id='button' rel='"+ plus +"' /></td><tr>");
var count = jQuery.('#button').attr('rel');
if(count=5){
alert('Limit reached');
}
})
THanks

You have to put the counter variable outside the event handler, otherwise you will be starting over from zero each time.
You should put the code that adds the elements inside the if statement, so that you either show a messare or add the elements.
There is no point in reading the value from the button that you just added, when you already have the value. Besides, an id should be unique, so you would not get the value from the last button but the first.
The comparison operator is ==, if you use = you will instead assign a value to the variable, so the condition would always end up being true.
$(document).ready(function(){
var sliderCount = 0;
jQuery('#add_slider_image').click(function() {
if (sliderCount == 5) {
alert('Limit reached');
} else {
sliderCount++;
jQuery('.form-table').append('<tr><td><input type="text" value="" name="slider[]" /><input type="button" name="sliderbut" value="Upload" rel="'+ sliderCount +'" /></td><tr>');
}
});
});

I guess something like this should work:
jQuery('#add_slider_image').click(function() {
var count = jQuery("input[name='sliderbut']").length;
if (count < 5){
jQuery('.form-table').append("<tr><td><input type='text' value='' name='slider[]' /><input type='button' name='sliderbut' value='Upload' /></td><tr>");
}
})
A bit simplified fiddle there: http://jsfiddle.net/Daess/fukxu/

When you try to compare the "count" with the number 5 you have to use == instead.
count = 5 will set count to 5 and always return true if you use count == 5 it will compare your variable with the number 5 and return true or false, depending on the value of the variable.
Also I think you can easily count the number of buttons by using length, sth like: $('.button').length should return the number of elements with the class (not ID) "button".

var i = 0
var plus = ++i;
This part means that plus will always be zero and i == 1, so your rel attribute always reads 0.
var count = jQuery.('#button').attr('rel');
You are using an ID selector. And ID can exist only once per page. As you use an ID selector, you get only the first matched element which will obviously not be the one you want as you want the number in the last element.
if(count=5){
..but it doesn't matter anyway because now you're just telling that count equals 5 and the alert will always execute. What you are looking for is the comparison operator ==.
Easiest way to do this is to ditch the counts and whatnots, and just check if there are already too many elements before inserting:
jQuery('#add_slider_image').click(function() {
if($('.form-table .myRow').length < 5) {
jQuery('.form-table').append('<tr class="myRow"><td><input type="text" name="slider[]" /><input type="button" name="sliderbut" value="Upload" class="button" /></td><tr>');
}
});
Note that I added the myRow class to help identify which rows are appended and changed the id="button" to class="button".

Try this.
jQuery('#add_slider_image').click(function() {
var myHTML = "";
var current_count = jQuery('.form-table tr').length();
if (current_count >= 5) return;
for (var i = current_count; i <= 5; i++) {
myHTML += "<tr><td><input type'text' value='' name='slider[]' /><input type='button' name='sliderbut' value='Upload' id='button" + plus + "' rel='" + plus + "' /></td><tr>";
}
//touch DOM once
jQuery('.form-table').append(myHTML);
});

Related

Generate random images from user checkboxed selections

Hi I have two sets of code. The first one was made by a nice person on this site, and generates a random letter based on the selections checkboxed by the user.
The second is one I found online. It allows you to turn image links into checkboxes that can be checked and unchecked.
I am trying to combine these two codes so that I can have the program generate a random image (instead of a letter) based on an array of images (again instead of letters) that the user checkboxes. In short, I'm trying to get something like the first set of code that uses images instead of letters.
Then, the final thing I'm trying to do is add a range slider like so (https://www.w3schools.com/code/tryit.asp?filename=GJ5U82DC2JX9) underneath each image. I want the user to be able to use the slider to "weight" the frequency of each checked image in the final randomization (with a range of 0 to 10).
Here is the first program in running form:
https://www.w3schools.com/code/tryit.asp?filename=GJ5TXX8V9B7L
Here is the second program in running form:
https://www.w3schools.com/code/tryit.asp?filename=GJ5TXEQM6HVI
I have tried intuitively copying and pasting from one set to the other, but I cant seem to get it even close to working the way I'd like. As for the weighting part, I am at a loss.
Thank you for any and all help, and if this is beyond the scope of help for this site I apologize.
Like that?
HTML Code:
<div id="formMatrix">
<ul>
</ul>
<input id="randomSubmit" type="submit" value="Randomize">
</div>
<div id="result">
<br />
<br />
</div>
JS Code:
function updateTextInput(val, i) {
document.getElementById('textInput-' + i).value = val;
}
document.addEventListener("DOMContentLoaded", function() {
//put your image's links
var images = ["http://townandcountryremovals.com/wp-content/uploads/2013/10/firefox-logo-200x200.png", "http://www.thebusinessofsports.com/wp-content/uploads/2010/10/facebook-icon-200x200.png", "http://tech21info.com/admin/wp-content/uploads/2013/03/chrome-logo-200x200.png"];
const form = document.getElementById("formMatrix");
const submitBtn = document.getElementById("randomSubmit");
const textResult = document.getElementById("result");
for (var i = 0; i < images.length; i++) {
form.getElementsByTagName('ul')[0].innerHTML += ("<li><input type='checkbox' id='chk-" + i + "' /><label for='chk-" + i + "'><img id='img-" + i + "' src='" + images[i] + "'/><div class='ranges'><input type='range' id='range-" + i + "' min='0' max='10' value='0' onchange='updateTextInput(this.value, " + i + ");' /><input type='text' disabled='disabled' id='textInput-" + i + "' value='0'/></div></label></li>");
}
// We check the values on the submit click
submitBtn.addEventListener("click", function(e) {
// Prevent it from *actually* submitting (e.g. refresh)
e.preventDefault();
// Grab *all* selected checkboxed into an array
const items = document.querySelectorAll("#formMatrix input:checked");
// Checking if it's not empty
if (items.length > 0) {
var array_items = [];
// Convert object to array
for (var i = 0; i < items.length; i++) {
array_items.push(items[i]);
}
// Add items by freq
for (var i = 0; i < array_items.length; i++) {
var n = parseInt(document.getElementById('textInput-' + array_items[i].id.split('-')[1]).value);
for (var j = 0; j < n; j++) {
array_items.splice(i + 1, 0, array_items[i]);
}
i = (i + n);
}
// Setting a random index from items[0] to items[items.length]
var imgid = ('img-' + array_items[Math.floor(Math.random() * array_items.length)].id.split('-')[1]);
textResult.innerHTML = ("<label><img id='imgResult' src='" + document.getElementById(imgid).src + "'/></label>");
} else {
// If not, we alert
alert("Please choose at least 1 image");
}
});
});
DEMO:
https://jsfiddle.net/pr0mming/vfam3g05/31/
What I really don't understand is the slide part, do you mean that each image can have a "weighting" number, which means that the larger the number, the more frequent it should be output?
UPDATE 1:
The simplest way I saw was to temporarily work the array of selected images, then, if the weight is 10, 10 more images will be inserted into the array respecting the order and it will be chosen randomly.
UPDATE 2:
Last changes: https://jsfiddle.net/pr0mming/vfam3g05/33/

How to get the number of input tags containing certain text?

My goal is to flag when a user enters the same text into one input that matches at least one other input's text. To select all of the relevant inputs, I have this selector:
$('input:text[name="employerId"]')
but how do I select only those whose text = abc, for instance?
Here is my change() event that checks for duplicate text among all the inputs on the page. I guess I am looking for something like :contains but for text within an input.
var inputsToMonitorSelector = "input[type='text'][name='employerId']";
$(inputsToMonitorSelector).change(function() {
//console.log($(this).val());
var inputsToExamineSelector = inputsToMonitorSelector
+ ":contains('" + $(this).val() + "')";
console.log(inputsToExamineSelector);
if($(inputsToExamineSelector).length > 1) {
alert('dupe!');
}
});
Or is there no such selector? Must I somehow select all the inputsToMonitorSelector's and, in a function, examining each one's text, incrementing some local variable until it is greater than one?
With input you need to use [value="abc"] or .filter()
$(document).ready(function() {
var textInputSelector = 'input[type="text"][name="employerId"]';
$(textInputSelector).on('input', function() {
$(textInputSelector).css('background-color', '#fff');
var input = $(this).val();
var inputsWithInputValue = $(textInputSelector).filter(function() {
return this.value && input && this.value == input;
});
var foundDupe = $(inputsWithInputValue).length > 1;
if(foundDupe) {
console.log("Dupe found: " + input);
$(inputsWithInputValue).css('background-color', '#FFD4AA');
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="employerId" value="abc">
<input type="text" name="employerId" value="">
<input type="text" name="employerId" value="">
<input type="text" name="employerId" value="">
[value="abc"] means if the value is abc
[value*="abc"] * means if the value contains abc
[value^="abc"] ^ means if the value starts with abc
[value$="abc"] $ means if the value ends with abc
Note: :contains() not for inputs , and word text not used with inputs and <select>.. inputs and <select> has a value
In your case .. instead of using
$(inputsToExamineSelector).length > 1)
You may need to use .filter()
$(inputsToExamineSelector).filter('[value*="abc"]').length > 1)
OR
$('input[type="text"][name="employerId"]').filter(function(){
return this.value.indexOf('abc') > -1
// for exact value use >> return this.value == 'abc'
}).length;
And to use a variable on it you can use it like
'[value*="'+ valueHere +'"]'
Something like this works. Attach isDuplicated(myInputs,this.value) to a keyup event listener attached to each input.
var myInputs = document.querySelectorAll("input[type='text']");
function isDuplicated(elements,str){
for (var i = 0; i < myInputs.length; i++) {
if(myInputs[i].value === str){
myInputs[i].setCustomValidity('Duplicate'); //set flag on input
} else {
myInputs[i].setCustomValidity(''); //remove flag
}
}
}
Here's another one. I started with vanilla js and was going for an answer like Ron Royston with document.querySelector(x) but ended up with jquery. A first attempt at several things but here you go:
$("input[type='text']").each(function(){
// add a change event to each text-element.
$(this).change(function() {
// on change, get the current value.
var currVal = $(this).val();
// loop all text-element-siblings and compare values.
$(this).siblings("input[type='text']").each(function() {
if( currVal.localeCompare( $(this).val() ) == 0 ) {
console.log("Match!");
}
else {
console.log("No match.");
}
});
});
});
https://jsfiddle.net/xxx8we6s/

How can I get form field values to sum up to another field value using javascript/jQuery?

I have the following html form fields that I need the sum of acct1, acct2 and acct3 to equal the value of the surcharge field.
<input type="text" name="surcharge" id="surcharge" class="gui-input" placeholder="xx.xx">
<input type="text" name="acct1" id="acct1" placeholder="xx.xx">
<input type="text" name="acct2" id="acct2" placeholder="xx.xx">
<input type="text" name="acct3" id="acct3" placeholder="xx.xx">
I have tried several variations of this thus far:
$('#surcharge').change(function(){
if( ( $('#acct1').val() + $('#acct2').val() + $('#acct3').val() ) == $('#surcharge') ){
alert("Values match Surcharge");
}
else {
alert("Values DO NOT match Surcharge");
}
});
The problem is that the val() method returns a string. It needs to be converted to an integer first. You can do that by calling Number() and wrapping the value inside the parentheses.
$('#surcharge').change(function(){
if( Number($('#acct1').val()) + Number($('#acct2').val()) + Number($('#acct3').val()) == $('#surcharge').val() ){
alert("Values match Surcharge");
}
else {
alert("Values DO NOT match Surcharge");
}
});
This is kind of tough to read though, so might be a better idea to break it down
$('#surcharge').change(function() {
var total = 0;
$("#acct1", "#acct2", "#acct3").each(function() {
total += Number($(this).val());
});
if (total == $('surcharge').val()) {
});
Try to cast the value to integer
parseInt($('#acct1').val())+parseInt($('#acct2').val());
You need to convert you field values to numbers. The default input field value is a string. At the moment you are adding strings. To get a number do this for all your fields (including surcharge):
parseFloat($('#acct1').val());
$('#surcharge,#acct1,#acct2,#acct3').keyup(function() {
console.log([parseInt($('#acct1').val()),parseInt($('#acct2').val()),parseInt($('#acct3').val()), parseInt($('#surcharge').val())]);
if (
(
parseInt($('#acct1').val()) + parseInt($('#acct2').val()) + parseInt($('#acct3').val())
) == parseInt(
$('#surcharge').val()
)
) {
alert("Values match Surcharge");
} else {
alert("Values DO NOT match Surcharge");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="acct1" value="1">+
<input id="acct2" value="1">+
<input id="acct3" value="1">=
<input id="surcharge" value="3">
You should change your listener to something like blur so the event doesn't trigger with every change (key press) on the surcharge field.
Also, add a class to all of your acct input fields so you can loop by the class:
$( "#surcharge" ).blur(function() {
var total = 0;
$(".acct").each(function() {
if($(this).val()) {
total += parseFloat($(this).val());
}
});
//you may want total.toFixed(2)
if(parseFloat($(this).val()) == total.toFixed(2)) {
alert("Values match Surcharge");
} else {
alert("boooo!");
}
});
And here's a JSFiddle demo.

Incrementing int by check marking a radio button

I have a whole bunch of radio buttons formatted in the following way;
<input type="radio" name="Xch" value="XCheese " onclick="incrementIndex()">XCheese<br>
and my incrementIndex() function is simple enough;
var index = 0;
function incrementIndex() {
index += 1;
document.getElementById("demo").innerHTML = ""+index+"";
if ($("#Xch").attr("checked") == true){
index = 10;
}
}
And when a radiobutton is clicked it increments the index, but I want it to increase the index once and only if the button is not checked, the way it is set up, even if the Xch radio button is checked, it keeps increment the index! Please help.
Not sure why you would want to do something like this, but is this what you were trying to do?
<input type="radio" name="ch" value="XCheese " onclick="incrementIndex(this)">XCheese</input><br>
<input type="radio" name="ch" value="YCheese " onclick="incrementIndex(this)">YCheese</input><br>
<input type="radio" name="ch" value="ZCheese " onclick="incrementIndex(this)">ZCheese</input><br>
var index = 0;
var previousValue;
function incrementIndex(e)
{
if(e.checked && e != previousValue) index += 1;
previousValue = e;
alert(index);
}
Here's an example
http://jsfiddle.net/Md8fj/134/
What you're doing isn't exactly clear, but if you want the desired behavior, move the index += 1 inside the if statement that detects if it's already checked. If it's not, then you can increment.
Something like:
var index = 0;
function incrementIndex() {
document.getElementById("demo").innerHTML = ""+index+"";
if ($("#Xch").attr("checked") == true){
index = 10;
}
else {
index += 1;
}
}
You need to use a checkbox instead of a radiobox.
In a radio group, once an input is selected, one input in the group must always remain selected.
In a checkbox group, any number if inputs can be selected or deselected.
Change your HTML to:
<input type="checkbox" name="Xch" value="XCheese " onclick="incrementIndex()">XCheese<br>
And it should work.

jQuery input forms issue

I'm currently working on some input forms in JavaScript, and I've edited by script so that once the user enters the number of forces for a problem, new input text fields show up per number, also there is a button which is added at the end of that. The issue is when I try and click this button, I try and use the .map function to start all text field values into it and nothing is happening.
function forceRecording(numofforces,$this){
var addRows='<tr id=newRows>';
for(var i =1; i<=numofforces;i++)
{
var nearTr=$this.closest('tr');
addRows=addRows + "<td>Force " +i+": </td><td><form><input type='text' name='forceItem' id='newR'/></form></td>";
}
addRows=addRows+"<td><div class='button' id='forceButton'> Add! </div></td></tr>";
nearTr.after(addRows);
};
$('#forceButton').click(function(){
forces=$("input[id='newR']").map(function(){
return $(this).val()
});
function forceRecording(numofforces,$this){
var addRows='<tr id=newRows>';
for(var i =1; i<=numofforces;i++)
{
var nearTr=$this.closest('tr');
addRows=addRows + "<td>Force " +i+": </td><td><form><input type='text' name='forceItem' id='newR'/></form></td>";
}
addRows=addRows+"<td><div class='button' id='forceButton'> Add! </div></td></tr>";
nearTr.after(addRows);
};
$('#forceButton').click(function(){
forces=$("input[id='newR']").map(function(){
return $(this).val()
});
prompt("forces");
});
As you can see my forceRecording function is working and creates a new row with new text input fields per the numofforces but once I try clicking the forceButton to enter the values into my forces array nothing happens. Any idea what could be causing this?
You are missing the closing paranthesis around your code here
$('#forceButton').click(function(){
forces=$("input[id='newR']").map(function(){return $(this).val()
});
It should be like this
$('#forceButton').click(function(){
forces=$("input[id='newR']").map(function(){
return $(this).val();
});
});
And don't use the id instead use a class name
$('#forceButton').click(function(){
forces=$(".newR").map(function(){
return $(this).val();
});
});
Apply the class to input field like this
<input type="text" name="forceItem" class="newR"/>
I have absolutely no idea what you're trying to achieve, but maybe this will help:
function forceRecording(numofforces, $this) {
var addRows = '<tr id="newRows">';
for (var i = 1; i <= numofforces; i++)
addRows += '<td>Force ' + i + ': </td><td><input type="text" name="forceItem" /></td>';
addRows += '<td><input type="button" class="button" id="forceButton" value="Add!" /></td></tr>';
$this.closest('tr').after(addRows);
}
$('#forceButton').click(function() {
forces = $(this).parent().parent().filter('input[name="forceItem"]').map(function() { return $(this).val(); });
});

Categories