Function variables don't work in jQuery? - javascript

Im making a jquery function, but im getting trouble with some variables. I cant get the value of #op1 to the input and in #z1 it shows "i" instead of "Start. Also the counter parameter doesnt add up. It only shows "0". In the click event it gets added up.
javascript code:
$(function() {
$(function () {
var inpreco = [];
var altpreco = [];
var cpcounter9 = 0;
$(".opcaopreco").click(function () {
SuperF(this, "#preco", "inpreco", "altpreco", "cpvalor", "cpindex",
"cpactive", "cpcounter9", "preco");
});
function SuperF(element, input, inpArray, secArray, inpValue, secIndex,
inpActive,
counter, msqlip) {
var inpValue = $("#" + element.id).val();
var secIndex = $("#" + element.id).data(secIndex);
var inpActive = $("#" + element.id).data(inpActive);
if (inpArray[0] == "") {
counter++;
$("#" + element.id + "l").addClass("activa");
$(element).data(inpActive, "primary");
inpArray[0] = (inpValue);
input.val(inpArray[0]);
}
$("#z1").html(inpArray[0]);
$("#z2").html(counter);
$("#z3").html(cpcounter9);
};
});
});
html code:
<input id="preco" type="text" name="preco" value=''><br><br>
<div id="op1l" class="input">
<input type="checkbox" id="op1" class="opcaopreco" value="Start" data-cpindex="1" data-cpactivo="">
<label for="op1"></label>
<span class="itext">Test</span>
</div>
<ul id="z">
<li id="z1">z1</li>
<li id="z2">z2</li>
<li id="z3">z3</li>
</ul>

You're passing in strings for your parameters, not elements. So when you index that parameter you're getting the first character in the string.
You need to use the strings as selectors to get their associated elements and then pass their return values into your function:
// use the strings to make a selection
var preco = $('#preco');
var inpreco = $('inpreco');
// etc.
// pass the results of each selection into your function
SuperF(this, preco, inpreco, ...)
You can do this inline as well:
SuperF(this, $("#preco"), $("inpreco"), ...)
Similarly, you have other variables you're trying to pass as strings, rather than passing them by name like this:
SuperF(this, $('#preco'), inpreco, altpreco, cpvalor, cpindex, cpactive, cpcounter9, preco);
That is the reason your function can't access most of the parameters and why your counter remains at 0.

Related

How would I assign each list item a sequential ID in Javascript? (in an html document by the way)

Here is the section which is confusing me:
<script type="text/javascript">
//declaring veriables
var inputField = document.getElementById("input");
var addBtn = document.getElementById("addBtn");
var html = "";
var x = 0;
addBtn.addEventListener('click', function(){
var text = inputField.value;
addToList(text);
})
//adds items to list
function addToList(text){
html += "<li id=(x+=1)><h4><input type='checkbox' id=(x+=1) onclick= 'clearspecifieditems()'>"+text+"</h4></li>";
document.getElementById("myList").innerHTML = html;
inputField.value = "";
}
//clears items
function clearspecifieditems(itemid)
{
//delete selected item
};
So the goal here is to create a to-do list (I'm new to coding). The addToList(text) function is supposed to create a new list item and assign a sequential ID to it. However, I cannot seem to figure out how to have it generate the ID. In addition, clearspecifieditems(itemid) is supposed to get the IDs of all the list items that are checked, and clear all of them.
For the first part of your question either use string concatenation similar to how you added the text variable...
function addToList(text) {
const id = x + 1;
html += '<li id="' + id + '"><h4><input type="checkbox" id="' + id + '">' + text + '</h4></li>';
// ..
}
...or use a template literal:
function addToList(text) {
const id = x + 1;
html += `<li id="${id}"><h4><input type="checkbox" id="${id}" />${text}</h4></li>`;
// ..
}
HOWEVER, for the second part, how to clear checked boxes:
I purposely left the onclick out of the above code because it sounds as if you need a separate button to clear the checkboxes:
// Grab the button and add an click listener to it
// to call `clearSpecifiedItems`
const button = document.querySelector('.clear');
button.addEventListener('click', clearSpecifiedItems, false);
function clearSpecifiedItems() {
// Select all the checked checkboxes using their class
const selected = document.querySelectorAll('.test:checked');
// Set their checked property to false (or null)
selected.forEach(input => input.checked = false);
}
<input class="test" type="checkbox" />
<input class="test" type="checkbox" />
<input class="test" type="checkbox" />
<input class="test" type="checkbox" />
<button class="clear">Clear</button>
Notice that none of these inputs have IDs. I've used a class to pick up the elements instead. So unless you're using the ids for anything else it makes the first part of your code redundant. Just use a CSS selector to grab the elements you need and then process them. No IDs required!
I can see what you're going for. You are almost there. Just a little bit of syntactical error, and a bit of a logical one.
You see, when you increment x two times, You will have a different id for the <li> and the <input>. What I suggest is you increment the x beforehand and then use it.
You can do it like this:
function addToList(text){
x++;
html += "<li id="+ x +"><h4><input type='checkbox' id="+ x +" onclick= 'clearspecifieditems()'>"+text+"</h4></li>";
document.getElementById("myList").innerHTML = html;
inputField.value = "";
}
or this (ES6)
function addToList(text){
x++;
html += `<li id=${x}><h4><input type='checkbox' id=${x} onclick= 'clearspecifieditems()'>${text}</h4></li>`;
document.getElementById("myList").innerHTML = html;
inputField.value = "";
}
Is it absolutely necessary that you must only increment? Can the ID's be truly unique? I suggest you use UUID in that case
Your second question is how to make clearspecifieditems work. Here's what you can do. You can pass the context, or simply the checkbox that was clicked and then get it's ID easily..
So you would define your function something like this:
function clearspecifieditems(element){
//delete selected item
console.log(element.id); // this would give you the ID of the selected checkbox and then you can do whatever with it
};
and slightly modify your function call on the click event
html += "<li id="+ x +"><h4><input type='checkbox' id="+ x +" onclick= 'clearspecifieditems(this)'>"+text+"</h4></li>";
Note this this part.
More more information, See this
Just use string interpolation to reference the x variable and increment it by one every time you add a new item as follows:
/* JavaScript */
var inputField = document.getElementById("input");
var addBtn = document.getElementById("addBtn");
var output = document.getElementById("output");
var html = "";
var x = 0;
function addToList(text) {
output.innerHTML += `<li id=id${x}><h4><input type='checkbox' id=${x}>This list item has an id: id${x}"</h4></li>`;
inputField.value = "";
x++;
}
addBtn.addEventListener('click', function(){
var text = inputField.value;
addToList(text);
})
<!-- HTML -->
<input type="text" id="input" />
<button id="addBtn">Add Items</button>
<div id="output"></div>
And for removing checked elements, simply add another button, say removeBtn and then add a click listener to the button that invokes the clearspecifieditems().
Inside the function, assign a variable to a list of all the checkboxes, loop through the variable using forEach and remove any checkbox that is not checked like this:
function clearspecifieditems() {
var check = document.querySelectorAll('[id^="id"]');
check.forEach(checkBox => {
if(checkBox.children[0].children[0].checked){
checkBox.remove();
}
});
}
removeBtn.addEventListener('click', clearspecifieditems);
#output {list-style: none;}
/* <input type="text" id="input" />
<button id="addBtn">Add Items</button> */
<ul id="output">
<li id="id0"><h4><input type="checkbox" id="input0">This list item has an id: id0"</h4></li>
<li id="id1"><h4><input type="checkbox" id="input1">This list item has an id: id1"</h4></li>
<li id="id2"><h4><input type="checkbox" id="input2">This list item has an id: id2"</h4></li>
<li id="id3"><h4><input type="checkbox" id="input3">This list item has an id: id3"</h4></li>
</ul>
<hr>
<button id="removeBtn">Remove</button>
You're sending X as 1. You should do like this :
var input = document.getElementById("input");
var div = document.getElementById("div");
var button = document.getElementById("addbutton");
var id = 0;
button.onclick = function() {
text = input.value;
addtask(text)
}
function addtask(text) {
var element = document.createElement("li");
element.setAttribute("id", id)
var deleteE = document.createElement("input");
deleteE.setAttribute("type", "checkbox");
deleteE.setAttribute("onclick", "deleteX(" + id + ")");
var node = document.createTextNode(text);
element.appendChild(deleteE);
element.appendChild(node);
div.appendChild(element);
id += 1;
}
function deleteX(id) {
document.getElementById(id).style.visibility = "hidden";
}
<input id="input"> <button id="addbutton"> add </button>
<div id="div"></br> </div>

Can't grab value from hidden element

For some reason I get a javascript on the following code:
var teamOne = "";
var teamTwo = "";
var children = $(this).find(".team-url");
if (children.length === 2) {
teamOne = children[0].val();
teamTwo = children[1].val();
}
alert(teamOne + " - " + teamTwo);
The error is on .val() The code finds 2 elements and then it can't take the value. If I remove .val() I get it saying it is an [Object HTMLInputElement]
The error is
Uncaught TypeError: children[0].val is not a function
Note:
I Know that I can get this code to work by doing the following:
var teamOne = "";
var teamTwo = "";
var children = $(this).find(".team-url");
if (children.length === 2) {
teamOne = children.first().val();
teamTwo = children.last().val();
}
alert(teamOne + " - " + teamTwo);
However, I am trying to understand why my first version doesn't work so that I can have a better understanding of these functions.
EDIT:
HTML
<div class="col-md-12 game" style="margin-top: 10px">
<div class="team-details">Team Saturn
<input type="hidden" class="team-url" value="TeamSaturn">
</div>
<div class="team-details">Team Datarnan
<input type="hidden" class="team-url" value="TeamDatarnan">
</div>
</div>
Try this:
HTML
<input type="hidden" value="value 1" class="team-url" />
<input type="hidden" value="value 2" class="team-url" />
JS
var teamOne = "";
var teamTwo = "";
var children = $('body').find(".team-url");
if (children.length === 2) {
debugger;
teamOne = children[0].value;
teamTwo = children[1].value;
}
alert(teamOne + " - " + teamTwo);
In your code "$(this)" is not in the real context, and I have changed it with a global search in "body".
The JSFiddle
There is no function val on a HTMLInputElement Object. As children[0] is not a jQuery element you can not use the jQuery function val on it. But you can use the native javascript for this:
You can use teamOne = children[0].value;
First thing is that children[0] returns the DOM element not jQuery object, so you need to use children[0].value instead. To get a jQuery object, you should use .eq(0), .first(), .last() etc.
Second is that $(this).find() has no context. You could use either $('body').find(".team-url") or just $(".team-url")

In Jquery take a different values from single text box id

I am using Data Table in jquery. So i passed one input type text box and passed the single id. This data table will take a multiple text box. i will enter values manually and pass it into the controller. I want to take one or more text box values as an array..
The following image is the exact view of my data table.
I have marked red color in one place. the three text boxes are in same id but different values. how to bind that?
function UpdateAmount() {debugger;
var id = "";
var count = 0;
$("input:checkbox[name=che]:checked").each(function () {
if (count == 0) {
id = $(this).val();
var amount= $('#Amount').val();
}
else {
id += "," + $(this).val();
amount+="," + $(this).val(); // if i give this i am getting the first text box value only.
}
count = count + 1;
});
if (count == 0) {
alert("Please select atleast one record to update");
return false;
}
Really stuck to find out the solution... I want to get the all text box values ?
An Id can only be used once; use a class, then when you reference the class(es), you can loop through them.
<input class="getValues" />
<input class="getValues" />
<input class="getValues" />
Then, reference as ...
$(".getValues")
Loop through as ...
var allValues = [];
var obs = $(".getValues");
for (var i=0,len=obs.length; i<len; i++) {
allValues.push($(obs[i]).val());
}
... and you now have an array of the values.
You could also use the jQuery .each functionality.
var allValues = [];
var obs = $(".getValues");
obs.each(function(index, value) {
allValues.push(value);
}
So, the fundamental rule is that you must not have duplicate IDs. Hence, use classes. So, in your example, replace the IDs of those text boxes with classes, something like:
<input class="amount" type="text" />
Then, try the below code.
function UpdateAmount() {
debugger;
var amount = [];
$("input:checkbox[name=che]:checked").each(function () {
var $row = $(this).closest("tr");
var inputVal = $row.find(".amount").val();
amount.push(inputVal);
});
console.log (amount); // an array of values
console.log (amount.join(", ")); // a comma separated string of values
if (!amount.length) {
alert("Please select atleast one record to update");
return false;
}
}
See if that works and I will then add some details as to what the code does.
First if you have all the textbox in a div then you get all the textbox value using children function like this
function GetTextBoxValueOne() {
$("#divAllTextBox").children("input:text").each(function () {
alert($(this).val());
});
}
Now another way is you can give a class name to those textboxes which value you need and get that control with class name like this,
function GetTextBoxValueTwo() {
$(".text-box").each(function () {
alert($(this).val());
});
}

Extract data using regular expression

I have these text fields.
<input type="text" value="<p>aaaaaaaaaaa</p>" id="tab_4_0_li_div_content"><input type="text" value="lab" id="tab_4_0_li_data"><input type="text" value="<p>dddd</p>" id="tab_4_1_li_div_content"><input type="text" value="client" id="tab_4_1_li_data">
Here tab_4_*_li_data is a <li> html of tab , and tab_4_0_li_div_content is id of <div> which will be show on <li> click.
Now I want to extract data from this input fields using regular expression. For example
client,lab
as key
and
<p>aaaaaaaaaaa</p>,<p>dddd</p>
as value of key.
If you see these are related to each others.
tab_4_0_li_div_content tab_4_0_li_data
<p>aaaaaaaaaaa</p> lab
tab_4_1_li_div_content tab_4_1_li_data
<p>dddd</p> client
Div content part can content any thing, It's an text area.
So how we do this?
There is no reason to have to use a regular expression to parse HTML. One thing, you are not going to have a good time going it. Second, use the power of the DOM
var contents = $("[id$=content]"); //find the elements that have an id that end with content
var datas = $("[id$=data]"); //find the elements that have an id that end with data
var details = {}; //object to hold results
datas.each( function(i) { details[datas[i].value] = contents[i].value; }); //start looping and generate the object with the details you are after
console.log(details); //Object {lab: "<p>aaaaaaaaaaa</p>", client: "<p>dddd</p>"}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="text" value="<p>aaaaaaaaaaa</p>" id="tab_4_0_li_div_content"><input type="text" value="lab" id="tab_4_0_li_data"><input type="text" value="<p>dddd</p>" id="tab_4_1_li_div_content"><input type="text" value="client" id="tab_4_1_li_data">
Now that code assumes the data and content elements are in the same order, if not, than it would require a little processing, but it is not that hard to do.
var datas = $("[id$=data]");
var details = {};
datas.each(function(i, elem) {
var id = elem.id;
var val = $("#" + id.replace("data", "div_content")).val();
details[elem.value] = val;
});
console.log(details); //Object {lab: "<p>aaaaaaaaaaa</p>", client: "<p>dddd</p>"}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="text" value="<p>aaaaaaaaaaa</p>" id="tab_4_0_li_div_content">
<input type="text" value="lab" id="tab_4_0_li_data">
<input type="text" value="<p>dddd</p>" id="tab_4_1_li_div_content">
<input type="text" value="client" id="tab_4_1_li_data">
You can do it like this:
function getValuesById(id1,id2){
var vals = {};
if(id1 === undefined)
id1 = "\\d+";
if(id2 === undefined)
id2 = "\\d+";
$("input").each(function (index, value) {
console.log(new RegExp('tab_(' + id1 + '_' + id2 + ')_li_data'));
var match = value.id.match(new RegExp('tab_(' + id1 + '_' + id2 + ')_li_data'));
if (match) {
vals[value.value] = $("#tab_" + match[1] + "_li_div_content").val();
}
});
return vals;
}
Here I search through all input fields and match against tab_DIGITS_DIGITS_li_div_data and put that as a key and corresponding li_div_content as value in object values.
Check it out here: JSFiddle
UPDATE: I have updated the code to a function where you can send in a parameter to your two numerical values and will use any number if not supplied, i.e. use as getValuesById(4) for values like tab_4_*_li

How to add array items to <li> Jquery

I'm working on something really simple, a short quiz, and I am trying to make the items I have listed in a 2-d array each display as a <li>. I tried using the JS array.join() method but it didn't really do what I wanted. I'd like to place them into a list, and then add a radio button for each one.
I have taken the tiny little leap to Jquery, so alot of this is my unfamiliarity with the "syntax". I skimmed over something on their API, $.each...? I'm sure this works like the for statement, I just can't get it to work without crashing everything I've got.
Here's the HTML pretty interesting stuff.
<div id="main_">
<div class="facts_div">
<ul>
</ul>
</div>
<form>
<input id="x" type="button" class="myBtn" value="Press Me">
</form>
</div>
And, here is some extremely complex code. Hold on to your hats...
$(document).ready (function () {
var array = [["Fee","Fi","Fo"],
["La","Dee","Da"]];
var q = ["<li>Fee-ing?","La-ing?</li>"];
var counter = 0;
$('.myBtn').on('click', function () {
$('#main_ .facts_div').text(q[counter]);
$('.facts_div ul').append('<input type= "radio">'
+ array[counter]);
counter++;
if (counter > q.length) {
$('#main_ .facts_div').text('You are done with the quiz.');
$('.myBtn').hide();
}
});
});
Try
<div id="main_">
<div class="facts_div"> <span class="question"></span>
<ul></ul>
</div>
<form>
<input id="x" type="button" class="myBtn" value="Press Me" />
</form>
</div>
and
jQuery(function ($) {
//
var array = [
["Fee", "Fi", "Fo"],
["La", "Dee", "Da"]
];
var q = ["Fee-ing?", "La-ing?"];
var counter = 0;
//cache all the possible values since they are requested multiple times
var $facts = $('#main_ .facts_div'),
$question = $facts.find('.question'),
$ul = $facts.find('ul'),
$btn = $('.myBtn');
$btn.on('click', function () {
//display the question details only of it is available
if (counter < q.length) {
$question.text(q[counter]);
//create a single string containing all the anwers for the given question - look at the documentation for jQuery.map for details
var ansstring = $.map(array[counter], function (value) {
return '<li><input type="radio" name="ans"/>' + value + '</li>'
}).join('');
$ul.html(ansstring);
counter++;
} else {
$facts.text('You are done with the quiz.');
$(this).hide();
}
});
//
});
Demo: Fiddle
You can use $.each to iterate over array[counter] and create li elements for your options:
var list = $('.facts_div ul');
$.each(array[counter], function() {
$('<li></li>').html('<input type="radio" /> ' + this).appendTo(list);
}
The first parameter is your array and the second one is an anonymous function to do your action, in which this will hold the current element value.
Also, if you do this:
$('#main_ .facts_div').text(q[counter]);
You will be replacing the contents of your element with q[counter], losing your ul tag inside it. In this case, you could use the prepend method instead of text to add this text to the start of your tag, or create a new element just for holding this piece of text.

Categories

Resources