simpler way of grouping numerous variables by value of select? - javascript

thanks for looking.
im still learning the more complex javascript and jquery coding so could do with some help as i have no idea about the following or even if its possible!
i need a better/simpler/shorter way of doing the following (please note i have removed the irrelevant validation etc coding):
'
function Findbox5( myform, box1, box2, box3, box4, box5, Storeall, s1, s2, s3, s4, s5)
{
//store values
Myform = document.forms.myform;
box1 = Myform.box1.value;
box2 = Myform.box2.value;
box3 = Myform.box3.value;
box4 = Myform.box4.value;
box5 = Myform.box5.value;
s1 = Myform.s1.value;
s2 = Myform.s2.value;
s3 = Myform.s3.value;
s4 = Myform.s4.value;
s5 = Myform.s5.value;
//set as one string
Storeall = s1 + ":" + box1 + ";" + s2 + ":" + box2 + ";" + s3 + ":" + box3 + ";" + s4 + ":" + box4 + ";" + s4 + ":" + box5 + ";" ;
// next function...
} '
as you can see i have 5 input boxes and relevant selects for each box(each select has 4 options:1,2,3,4.). when a user enters data into a box they choose a relevant option. all boxes and options must be entered then they submit the form.
this data will be emailed to me as the variable stored under storeall. which would be something like 1:1234;2:1324;1:3232;4:5434;2:3211;
so what i hope to do is simplify this data into the following with either a seperate function or the same one: 1:1234-3232;2:1324-3211;4:5434;
is this possible? or have i done it the easiest way?
any comments or help welcomed, thanks again

First, you'll want to group these things into a single element that can be iterated against. So if your HTML looks like:
<form>
<input name="s1" />
<input name="box1" />
<input name="s2" />
<input name="box2" />
...
</form>
Then it's probably better to do something like:
<form>
<div class="set">
<input class="s" name="s1" />
<input class="box" name="box1" />
</div>
<div class="set">
<input class="s" name="s2" />
<input class="box" name="box2" />
</div>
...
</form>
Now you've established some commonality among these elements, instead of just different names/IDs. Each set of inputs is grouped by the .set class, and within each set, you know there's going to be two inputs: one with the .s class, and one with the .box class. Now iterating against them with JQuery is easy:
var str = "";
$("form div.set").each(
function(index, element)
{
currentValueS = $(element).find("input.s").val();
currentValueBox = $(element).find("input.box").val();
str += currentValueS + ":" + currentValueBox + ";";
}
);
This uses JQuery's .each() function. .each() allows you to provide a function to perform on each of the elements that JQuery finds from the indicated selector. Here, your selector is form div.set, which means "all div elements that have the class of .set, and are found anywhere under any form element". For each of these elements, you'll need to find the value of the <input> element with the .s class, and also the value of the <input> element with the .box class. Then you just add those to your growing str variable.

If you want everything in the form, you should use serializeArray :
$('#my_form').submit(function() {
var str = '';
$.each($(this).serializeArray(), function () {
str += this.name + ":" + this.value + ";";
});
sendByMail(str);
return false;
});

Related

Problem with querySelector() not modifying value, onblur or onfocus in <input> tag

I must be screwing something up. When I try to use querySelector() in Javascript I can't seem to modify the value, onblur and onfocus clauses of an input tag but I can modify it's id and name using JavaScript. Help!
I cloned a chunk of HTML code with the following;
const newAdjustment = lastAdjustment.cloneNode(true);
The input tag I'm modifying looks like this;
<input type="text" class="form-control text-right entered-amount"
id="Amount15" name="Amount15" value="$3.00"
onfocus="deformatAmount(15)" onblur="recalc(15)">
</input>
I have no problem using querySelector() to modify the id and name of the input tag;
const originalSequenceNumber = 15;
const newSequenceNumber = originalSequenceNumber + 1;
const originalAIdName = 'Amount' + originalSequenceNumber;
const newAIdName = 'Amount' + newSequenceNumber;
newAdjustment.querySelector("#" + originalAIdName).id = newAIdName;
newAdjustment.querySelector("#" + newAIdName).name = newAIdName;
This leaves me with the following;
<input type="text" class="form-control text-right entered-amount"
id="Amount16" name="Amount16" value="$3.00"
onfocus="deformatAmount(15)" onblur="recalc(15)">
</input>
I then try to modify value, onblur and onfocus with the following;
const newAOnfocus = 'deformatAmount(' + newSequenceNumber + ')';
const newAOnblur = 'recalc(' + newSequenceNumber + ')';
newAdjustment.querySelector("#" + originalAIdName).value = "$0.00 ";
newAdjustment.querySelector("#" + newAIdName).onfocus = newAOnfocus;
newAdjustment.querySelector("#" + newAIdName).onblur = newAOnblur;
and nothing happened. newAOnFocus, newOnBlur and the input element are as follows;
newAOnfocus = deformatAmount(16)
newAOnblur = recalc(16)
newAdjustment = <input type="text" class="form-control text-right entered-amount" id="Amount16" name="Amount16" value="$3.00" onfocus="deformatAmount(15)" onblur="recalc(15)">
After I append the child to the document and use document.querySelector() I can modify the value but not the onblur or onfocus clauses. What am I doing wrong? What clause am I missing from querySelector()? By the way, there a three input and three button tags in newAdjustment and I'm having the same problem with all six.
Correction about .value
.value was updated correctly. The page reflected the correct value in .value but when I did a console.log() of newAdjustment it displayed the original value from the cloning (.cloneNode()). I'm wondering if I'm having the same problem with the rest, which means I'm actually not having a problem at all. More testing to follow.
You can use setAttribute on the input.
So
newAdjustment.querySelector("#" + originalAIdName).value = "$0.00 ";
newAdjustment.querySelector("#" + newAIdName).onfocus = newAOnfocus;
newAdjustment.querySelector("#" + newAIdName).onblur = newAOnblur;
Becomes
newAdjustment.querySelector("#" + originalAIdName).setAttribute("value", "$0.00 ");
newAdjustment.querySelector("#" + newAIdName).setAttribute("onfocus", newAOnfocus);
newAdjustment.querySelector("#" + newAIdName).setAtribute("onblur", newAOnblur);

Is there a simpler way to do this script?

I'm learning and trying to put together a little bit of jquery. Admittedly I'm finding it difficult to find a good basics guide, particularly, when adding multiple actions to one page.
I read somewhere that the document listener should only be used once. I believe I'm using it twice here, but not 100% sure how to bring it into one listener.
Also because I've been hacking bits of script together, I think I'm using parts of javascript and parts of jQuery. Is this correct?
A critique of the code below [which does work] and any advice on how best to approach learning jQuery would be most helpful. Thanks.
Script 1 styles a group of 3 radio buttons depending on which one is clicked.
Script 2 appends new inputs to the bottom of a form.
var stateNo = <?php echo $HighestPlayerID; ?> + 1;
$(document).on('click', 'input', function () {
var name = $(this).attr("name");
if ($('input[name="' + name + '"]:eq(1)')[0].checked) {
$('label[name="' + name + '"]:eq(1)').addClass('nostate');
$('label[name="' + name + '"]').removeClass('selected');
}
else {
$('label[name="' + name + '"]').removeClass('nostate selected');
if ($('input[name="' + name + '"]:eq(0)')[0].checked) {
$('label[name="' + name + '"]:eq(0)').addClass('selected');
}
else {
$('label[name="' + name + '"]:eq(2)').addClass('selected');
}
}
});
$(document).on('click', 'button[name=btnbtn]', function () {
var stateName = 'state[' + stateNo + ']';
var newPlayerAppend = `` +
`<tr><td>` +
`<input type="hidden" name="state['` + stateNo + `'][PlayerID]" value="` + stateNo + `" /></td>` +
`<td><input name="` + stateName + `[Name]" value="Name"></td>` +
`<td><input name="` + stateName + `[Team]" type="radio" value="A">` +
`<td><input name="` + stateName + `[Team]" type="radio" value="">` +
`<td><input name="` + stateName + `[Team]" type="radio" value="B">` +
`</td></tr>`;
$("tbody").append(newPlayerAppend);
stateNo++;
});
HTML for the 3 radio button inputs
<td class="Choice">
<label name="state[1][Team]" class="teampick Astate ">A
<input name="state[1][Team]" type="radio" value="A" />
</label>
<label name="state[1][Team]" class="smallx nostate ">X
<input name="state[1][Team]" type="radio" value="" checked />
</label>
<label name="state[1][Team]" class="teampick Bstate">B
<input name="state[1][Team]" type="radio" value="B" />
</label>
</td>
Some of the code can be written more concisely, or more the jQuery way, but first I want to highlight an issue with your current solution:
The following would generate invalid HTML, if it were not that browsers try to solve the inconsistency:
$("tbody").append(newPlayerAppend);
A tbody element cannot have input elements as direct children. If you really want the added content to be part of the table, you need to add a row and a cell, and put the new input elements in there.
Here is the code I would suggest, that does approximately the same as your code:
$(document).on('click', 'input', function () {
$('label[name="' + $(this).attr('name') + '"]')
.removeClass('nostate selected')
.has(':checked')
.addClass(function () {
return $(this).is('.smallx') ? 'nostate' : 'selected';
});
});
$(document).on('click', 'button[name=btnbtn]', function () {
$('tbody').append($('<tr>').append($('<td>').append(
$('<input>').attr({name: `state[${stateNo}][PlayerID]`, value: stateNo, type: 'hidden'}),
$('<input>').attr({name: `state[${stateNo}][Name]`, value: 'Name'}),
$('<input>').attr({name: `state[${stateNo}][Team]`, value: 'A', type: 'radio'})
)));
stateNo++;
});
There is no issue in having two handlers. They deal with different target elements, and even if they would deal with the same elements, it would still not be a real problem: the DOM is designed to deal with multiple event handlers.
There are 2 places you are using anonymous functions. If the code block moves to a named function, the entire code becomes more maintainable. It also helps better in debugging by telling you upfront which function name the error may lie in.
Once you have named functions you will realise that you really do have 2 event listeners for click. So there isn't much benefit of moving them in one listener (or one function you may be referring to). These both event listeners attach on document object and listen to a click event.
Class names are always better when hyphenated. a-state over Astate.
If it works it is correct code, for once you asked about correctness.
It is absolutely fine to have multiple listeners but I usually prefer making everything under one roof. Consider making code as simple as possible which saves lot of time during maintenance.
you can use $(function() {}) or document.ready().
$(document).ready(function() {
$('input[type="radio"]').click(function() {
var thisa = $(this).parent();
var name = $(this).attr("name");
// Remove :selected class from the previous selected labels.
$('label[name="' + name + '"]').removeClass('selected');
// Add conditional class with tenary operator.
thisa.parent().hasClass("smallx") ? thisa.addClass('nostate') : thisa.addClass('selected');
});
$('button[name=btnbtn]').click(function() {
var stateName = 'state[' + stateNo + ']';
// Add TR and TD before appending the row to tbody
var newPlayerAppend = `<tr><td>` +
`<input type="hidden" name="state['` + stateNo + `'][PlayerID]" value="` + stateNo + `" />` +
`<input name="` + stateName + `[Name]" value="Name">` +
`<input name="` + stateName + `[Team]" type="radio" value="A"></td></tr>`;
$("tbody").append(newPlayerAppend);
stateNo++;
});
});
Hope this helps.

Dynamic variable creation using eval JavaScript

I need something like an associative array that contains pairings of variable name / element ID.
Looping through this array/object, assign the element ID to the variable name that is its counterpart. Something like this:
jsFiddle
HTML:
<input id="fld_1" class="input" type="text" value="bob" /><br>
<input id="fld_2" class="input" type="text" value="fred" /><br>
<input id="fld_3" class="input" type="text" value="pat" /><br>
<input id="mybutt" class="btn" type="button" value="Test" />
JS:
objFields = {'f1':'fld_1', 'f2':'fld_2', 'f3':'fld_3'};
arrErrors = [];
$('#mybutt').click(function(){
alert('iii');
for (var key in objFields){
// eval(key = objFields[key]);
eval(key) = objFields[key];
alert('f1: ' +f1);
}
});
There is no requirement to using eval, I just need to turn the key into the variable name.
Where have I gone wrong?
Solution
JCOC611 got it right, but I wasn't clear in how I asked the question. As demo'd in this revised fiddle which implements JCOC611's solution, the variable/field names had to be used to get the value of the field contents, like this:
$('#mybutt').click(function(){
for (var key in objFields){
var tmp = objFields[key];
eval('var ' + key+ ' = $("#' +tmp+ '").val()');
}
});
If you know what you are doing and are absolutely sure about it, then use this:
eval(key + " = " + JSON.stringify(objFields[key]));
Or, if you want local variables:
eval("var " + key + " = " + JSON.stringify(objFields[key]));
Otherwise, I advice you implement one of the other answers.
You don't need that eval() at all, and you want to avoid it. All you really need to do is:
for (var key in objFields){
alert(key+': '+objFields[key]);
window[key] = objFields[key];
}
Will give you:
'f1':'fld_1'
'f2':'fld_2'
'f3':'fld_3'
Where:
f1 = 'fld_1';
f2 = 'fld_2';
f3 = 'fld_3';
If it is a global variable, it is as simple as:
window[key] = objFields[key];
or
window.key = objFields[key];
The second one is a bit less weird name immune.
The eval function runs a string add code and returns the result.
What your code did was evaluate the vague of key which is undefined and then tried to set it to a new value.
Is like writing 5=4;
Correct syntax:
eval('var ' + key + ' = ' + objFields[key]);

How can I make this feature faster in Javascript?

I have created a highlight feature that will highlight anything contained in a <p> red using a user specified keyword. When the submit button is clicked Javascript/jQuery pull the keyword from the input field and compare it to any lines that conain it and then highlight those lines red. It works great... but its slow. Is there another way to do this that is faster when working with over 1000 lines of <p>?
HTML
Keyword: <input type="text" id="highlight_box" class="text_box" value="--Text--" />
<input type="button" id="highlight" value="Highlight" />
<!--Print area for the Access log-->
<div id="access_content" class="tabbed-content">
<ul id="access-keywords-row" class="keywords-row">
<!--When a user submits a keyword it is placed as a tag here so it can be deleted later-->
</ul><br /><br />
<div id="access_log_print" class="print-area">
<p>Some Content</p>
<p>Some more content</p>
<!--Most of the time this could contain 1000's of lines-->
</div>
</div>
JavaScript
//add highlight and tag
$("#highlight").click(
function(){
var id = $("#highlight_box").val();
if(id == "--Text--" || id == ""){
alert("Please enter text before highlighting.");
}else{
$("#access-keywords-row").append("<li><img src=\"images/delete.png\" class=\"delete_filter\" value=\"" + id + "\" /> " + id + " </li>");
$("#access_log_print p:containsi(" + id + ")").css("color","red"); }
});
//remove highlight and tag
$(".keywords-row").on("click", ".delete_filter",
function() {
var val = $(this).val();
//remove element from HTML
$(this).parent().remove();
$("#access_log_print p:containsi(" + val + ")").css("color","black");
});
Adding color, red means adding the style attribute to each p, I think this can be improved adding a class:
p.highlight {
color:red;
}
And replacing
$("#access_log_print p:contains(" + id + ")").css("color","red");
by
$("#access_log_print p:contains(" + id + ")").addClass('highlight');
This probably speeds a little bit the process
I've written a small solution using jQuery's contains() method. Obviously you can throw in some string validation.
http://jsfiddle.net/W2CZB/
Try defining a css class, e.g.:
.red{background-color:#f00;}
and then instead of adding to each "style=background-color:#f00;" you will just .addClass("red");
just less code to put, but still jQuery will have to go thru all lines and if it is a lot then I guess it depends on your machine speed ;)
The following solution will probably increase performance at the cost of space. It works by building a word mapping of the lines and accessing directly to add or remove the highlight class. This solution also keeps a count of the number of times a filter hit that line so it stays highlighted until the last filter is removed. I have tested with a few lines, I am not sure how will it perform with 1000s. You tell us :)
$(function(){
buildIndex();
$("#highlight").click(
function(){
var id = $("#highlight_box").val();
if(id == "--Text--" || id == ""){
alert("Please enter text before highlighting.");
}else{
var filter = $("<li><img src=\"images/delete.png\" class=\"delete_filter\" value=\"" + id + "\" /> " + id + " </li>");
filter.click(function(){
$(this).remove();
removeHighlight(id)
});
$("#access-keywords-row").append(filter);
$.each(index[id], function(i,line){
if (line.highlightCount)
line.highlightCount++;
else {
line.addClass('highlight')
line.highlightCount=1;
}
});
}
});
function removeHighlight(id) {
$.each(index[id], function(i,line){
line.highlightCount--;
if (line.highlightCount<1)
line.removeClass('highlight')
});
};
});
var index={};
function buildIndex(){
$("#access_log_print p").each(function(i) {
var line = $(this)
var words = line.text().split(/\W+/);
$.each(words, function(i,word){
if (!index[word]) { index[word]=[]; }
index[word].push(line);
});
});
}

Need help with regular expression and javascript

I've following problem: I use a clone script to clone input fields which are used for cms options. Depending on the field name the option arrays are created in the db.
I have following field at the moment:
options[categories][1][3]
and want to increase the first number by using a counter variable like:
options[categories][2][3]
options[categories][3][3]
...
However I'm not familiar with regular expressions so I hoped someone could provide a str.replace code which helps me to replace the first number with my counter variable.
Thanks in advance!
.......
Code:
.......
At the moment it looks like:
if ( $(clone).attr('name') ){
newid = $(clone).attr('name');
var position = newid.lastIndexOf("[");
newid = newid.substring(0, position)+ '[' + (counter +1) + ']';
$(clone).attr('name', newid);
};
Html field:
<input type="checkbox" value="1" name="options[categories][1][3]">
3 is the category id, 1 is the option I need the category for. The clone script would produce:
<input type="checkbox" value="1" name="options[categories][1][4]">
at the moment - but I need:
<input type="checkbox" value="1" name="options[categories][2][3]">
I think it's a regex problem because the easiest solution would be to search for [categories][anyvalue] and replace it with [categories][counter]
You could use a regular expression to replace the first number in brackets. Like this:
if ( $(clone).attr('name') ) {
var newid = $(clone).attr('name');
newid = newid.replace(/\[[0-9]*\]/, '[' + (counter + 1) + ']');
$(clone).attr('name', newid);
};

Categories