I am using a series of check boxes all are with different name that is checkbox1....checkbox40. I am generating a series of sting with '1' and '0' that is if check box is checked than sting will be concatenated with '1' else it will be concatenated with '0'. I have successfully implemented idea for PHP but as now I am using Ajax I want to develop same code for java script. My PHP code for that is
if (isset($_POST[submit]))
{
for ($i=1; $i<41; $i++)
{
$walue = "restriction".$i;
if(isset($_POST[$walue])) {$val .="1";} else {$val .="0";}
}
}
echo "Equivalent String: ".$val."<p>";
for implementing it using Javascript I have called a function on submit event of form.
My form id is theForm and my checkboxes name is restriction1....restriction40. Please give me hint to implement the idea.
So.. something like this?
getCheckedString = function () {
var chunks = [];
var checkboxes = $("#theForm").children('input[type=checkbox]').each(function () {
chunks[chunks.length] = $(this).is(':checked') ? '1' : '0';
});
return chunks.join('');
}
This will gather up all of the checkboxes in the order they are on the form, put a '1' or '0' in the array, then return the array joined into a string. It's not specific to a particular name, so if there are other checkboxes in the form let me know and I'll alter my answer.
If you have only named checkboxes, you would do:
function getCheckedString1() {
var val = "";
for (var i = 1; i <= 40; ++i) {
var boxes = document.getElementsByName("restriction" + i); // returns an array
if (boxes[0]) {
val += boxes[0].checked ? "1" : "0";
}
}
// alert(val);
return val;
}
However, it is easier and the usual praxis to identify the referenced HTML elements with ID's. So, you would enhance your HTML:
<input type="checkbox" name="restriction1" id="restriction1" ...
<input type="checkbox" name="restriction2" id="restriction2" ...
and then use:
function getCheckedString2() {
var val = "";
for (var i = 1; i <= 40; ++i) {
var box = document.getElementById("restriction" + i); // returns the unique element
if (box) {
val += box.checked ? "1" : "0";
}
}
// alert(val);
return val;
}
Related
I'm trying to take user input from within an HTML file, convert it, and output it back to the page using <input> rather than prompt.
Here's what I have so far.
function bhedTester() {
alpha = "ABC";
bhed = "JYI";
btext = "";
i = 0;
while (i < norm.length) {
ind = alphabet.indexOf(norm.charAt(i));
btext = btext + bhed.charAt(ind);
i++;
}
btext
}
I've tested this using the prompt command and it works, but when I go to use
document.getElementById
OR
document.form_name._input_name.value
and then return that neither seems to work.
Can anyone advise?
If you're triggering this function from a DOM event you have to return btext.
function bhedTester() {
var alpha = "ABC";
var bhed = "JYI";
var btext = "";
var i = 0;
while (i < norm.length) {
var ind = alphabet.indexOf(norm.charAt(i));
btext = btext + bhed.charAt(ind);
i++;
}
return btext
}
To write to a div you will have to do:
document.getElementById("yourDiv").innerHTML= bhedTester();
And after that you will need to return a string from the function you wrote.
Right now it is not returning anything.
So your code should look like:
function bhedTester() {
alpha = "ABC";
bhed = "JYI";
btext = "";
i = 0;
while (i < norm.length) {
ind = alphabet.indexOf(norm.charAt(i));
btext = btext + bhed.charAt(ind);
i++;
}
return btext;
}
Since I don't know your norm and alphabet can't give you an exact solution.
You need to listen for when either the text is changed in the input or when the button is clicked. Your code just runs when the page loads. It does not magically run when you type text. You need to alter it to run when the user changes the text. So you need to use addEventListener to bind the event.
//bind the change event
document.getElementById("foo").addEventListener("change", function(){
var textbox = this, //reference the textbox
value = this.value; //get what the user typed
document.getElementById("bar").innerHTML = value; //set the value
});
<input type="text" id="foo" />
<div id="bar" />
Now if you want to run it when the user is typing, than use the keyup event.
I can get div elements by id and using only partial name "first"
html
<div id="first.1.end">first.1.end</div>
<div id="first.2.end">first.2.end</div>
<div id="two.3.end">two.3.end</div>
<div id="first.4.end">first.4.end</div>
js
function getElementsByIdStartsWith(selectorTag, prefix) {
var items = [];
var myPosts = document.getElementsByTagName(selectorTag);
for (var i = 0; i < myPosts.length; i++) {
if (myPosts[i].id.lastIndexOf(prefix, 0) === 0) {
items.push(myPosts[i]);
}
}
return items;
}
var postedOnes = getElementsByIdStartsWith("div", "first");
alert(postedOnes.length);
It counts 3 div elements (alert).
But how can I use end-partial name for search? For example using "end"?
From MDN Attribute selectors:
[attr^=value] Represents an element with an attribute name of attr and
whose value is prefixed by "value".
[attr$=value] Represents an element with an attribute name of attr and
whose value is suffixed by "value".
So you can use [id^="first"] to find elements with id start with "first". and use [id$="end"] to find elements end with "end".
Like
// This find all div which id ends with "end".
var divs = document.querySelectorAll('div[id$="end"]');
or use jQuery:
$('div[id$="end"]');
Also, you can combine multiple attribute selectors altogether to find a more specific element:
// As we only use querySelector, it find the first div with id starts with "two" and ends with "end".
var divStartAndEnd = document.querySelector('div[id^="two"][id$="end"]');
See demo on jsfiddle
Here I am allowing user to pass all three parameters.
suppose user doesn't pass midmatch so it will return only match of first and last.
Below is the working code:
It will return 1 count:
function getElementsByIdStartsWith(selectorTag, firstmatch, midmatch, lastmatch) {
var items = [];
var myPosts = document.getElementsByTagName(selectorTag);
for (var i = 0; i < myPosts.length; i++) {
var firstmatchIndex = firstmatch?myPosts[i].id.indexOf(firstmatch)>-1?true : false : true;
var midmatchIndex = midmatch?myPosts[i].id.indexOf(midmatch)>-1?true : false : true;
var lastmatchIndex = lastmatch?myPosts[i].id.indexOf(lastmatch)>-1?true : false : true;
if (firstmatchIndex && midmatchIndex && lastmatchIndex ) {
items.push(myPosts[i]);
}
}
return items;
}
var postedOnes = getElementsByIdStartsWith("div", "first", "2", "end");
alert(postedOnes.length); // now it will show only one in alert.
It will return 3 count:
function getElementsByIdStartsWith(selectorTag, firstmatch, midmatch, lastmatch) {
var items = [];
var myPosts = document.getElementsByTagName(selectorTag);
for (var i = 0; i < myPosts.length; i++) {
var firstmatchIndex = firstmatch?myPosts[i].id.indexOf(firstmatch)>-1?true : false : true;
var midmatchIndex = midmatch?myPosts[i].id.indexOf(midmatch)>-1?true : false : true;
var lastmatchIndex = lastmatch?myPosts[i].id.indexOf(lastmatch)>-1?true : false : true;
if (firstmatchIndex && midmatchIndex && lastmatchIndex ) {
items.push(myPosts[i]);
}
}
return items;
}
var postedOnes = getElementsByIdStartsWith("div", "first", "", "end");
alert(postedOnes.length); // now it will show only three in alert.
if you don't want to consider any parameter just pass empty string( "" ) while calling the function.
Hope this will help you :)
I guess this kind of selection can be possible by using jQuery + regex. Have a look to this
How can I select an element by ID with jQuery using regex?
Might be some what on the line that you want.
So I have a function where the text of one div replaces another,
I got the code working fine, however I wonder if there is a nice dynamic way to abstract the code so I get a shorter snippet, and thus I don't have to repeat the code over and over for each "pair" of divs?
My JS:
var correctAnswer1 = $('#q1').text();
$('#c1').text(correctAnswer1);
var correctAnswer2 = $('#q2').text();
$('#c2').text(correctAnswer2);
var correctAnswer3 = $('#q3').text();
$('#c3').text(correctAnswer3);
If you allready know the number of pairs you coud do something like this:
var numberOfQuestions = 5;
for(i = 0; i < numberOfQuestions; i++)
{
var answer = jQuery("#q"+i).text();
jQuery("#c"+i).text(answer);
}
Give all the #qN elements the question class.
$(".question").each(function () {
var cid = "#c"+$(this).attr("id").substr(1);
$(cid).text($(this).text());
});
i this this will work
function setTxtVal(id){
if(typeof id == "string"){
var sec = id.charAt(id.length - 1);
$("#c"+sec).text( $("#"+id).text() )
}
if(typeof id == "object"){
var x ,s;
for (x in id) {
var s = x.charAt(x.length - 1);
$("#c"+s).text( $("#"+x).text() )
}
}
setTextVal("c1")
or
setTextVal(["c1", "c3", "c4"])
or u can make a jquery plugin
$('[id^=q]').each(function(index){
$('#c' + index).html($(this).html());
});
Somtething like this
Do you have to do anything special while passing in a dynamically created string as a clientID for document.getElementById?
I have a asp:gridview control that has a textbox column and a checkbox column. I added an onclick event to the checkboxes to set the textbox value of that row to the max value of all checked rows +1. I pass in the IDs of the grid and the controls of the row that was selected. I can getElementByID fine for these controls, but When I dynamically build the IDs of the other controls, I keep getting null, even though I know that the IDs are correct. My code is bellow.
function SetPriority(cbID, tbID, gridID) {
var cb = document.getElementById(cbID);
if (cb.checked) {
var tb = document.getElementById(tbID);
var grid = document.getElementById(gridID);
var maxv = 0;
for (var i = 0; i < grid.rows.length; i++) {
var indexID = 102 + i;
var cbClientID = 'LeaveInfo_pnlMain_wgbLeaveSummary_gridSubmitted_ct' + indexID + '_chkGroup';
var tbClientID = 'LeaveInfo_pnlMain_wgbLeaveSummary_gridSubmitted_ct' + indexID + '_txtPriority';
console.log("row" + i);
//just for example of how it should be working
console.log(cbID);
var cbx = document.getElementById(cbID);
console.log(cbx);
//get row checkbox
console.log(cbClientID);
var thisCB = document.getElementById(cbClientID);
console.log(thisCB);
//get row textbox
var thisTB = document.getElementById(tbClientID);
console.log(thisTB);
if (thisCB) {
if (thisCB.type == "checkbox") {
if (thisCB.checked) {
if (thisTB.value > maxv)
maxv = thisTB.value;
}
}
}
}
tb.value = parseInt(maxv) + 1;
}
}
Here is how its showing up in the console, where you can see the IDs for the first row are the same
For Those wondering about How I am calling the function, I am adding it on to a checkbox in a .net gridview control on row databind. It renders as follows:
<input id="LeaveInfo_pnlMain_wgbLeaveSummary_gridSubmitted_ctl02_chkGroup" type="checkbox" name="LeaveInfo$pnlMain$wgbLeaveSummary$gridSubmitted$ctl02$chkGroup" onclick="javascript:SetPriority('LeaveInfo_pnlMain_wgbLeaveSummary_gridSubmitted_ctl02_chkGroup','LeaveInfo_pnlMain_wgbLeaveSummary_gridSubmitted_ctl02_txtPriority','LeaveInfo_pnlMain_wgbLeaveSummary_gridSubmitted');">
The vb .net code to add the function is this...(on-_RowDataBound)
Dim chk As CheckBox = CType(e.Row.FindControl("chkGroup"), CheckBox)
Dim tb As TextBox = CType(e.Row.FindControl("txtPriority"), TextBox)
chk.Attributes.Add("onclick", String.Format("javascript:SetPriority('{0}','{1}','{2}');", chk.ClientID, tb.ClientID, gridSubmitted.ClientID))
No, you don't have to do anything special when dynamically building a string. A string in javascript is the same string whether it was built dynamically or specified directly in your code. If document.getElementById() is not working, then one of the following is likely the cause:
Your string isn't what you think it is so it doesn't match the target id.
Your DOM id isn't what you think it is.
You have multiple elements with the same id (not likely here because you won't get null)
You are calling getElementById() before the DOM is ready or before the desired elements have been added to the DOM.
In this case, it seems more likely that 1) or 2) are the issues here, but you don't show us any context to know whether 4) could be the problem.
Not 100% sure, but I think it could be a context issue. Try this:
function ( id ) {
var ID = document.getElementById;
this.id = id;
this.newvar = ID.call( document, this.id );
...
}
Also, this question may help you — it has a good explanation on context and assigning a var to getElementById Why can't I directly assign document.getElementById to a different function?
I couldnt figure out why my IDs that seemed identical were not. I will leave this question open for anyone to add insight on how to remedy this. I ended up just getting my elements by cell and not by ID.
function SetPriority(cbID, tbID, gridID) {
var cb = document.getElementById(cbID);
if (cb.checked) {
var tb = document.getElementById(tbID);
var grid = document.getElementById(gridID);
var maxv = 0;
if (grid.rows.length > 0) {
for (row = 1; row < grid.rows.length; row++) {
var thisCB = grid.rows[row].cells[5].childNodes[1];
if (thisCB == cb) {
continue;
}
var thisTB = grid.rows[row].cells[6].childNodes[1];
if (thisCB.type == "checkbox") {
if (thisCB.checked) {
if (thisTB.value > maxv)
maxv = thisTB.value;
}
}
}
}
tb.value = parseInt(maxv) + 1;
}
}
I am creating a program using JavaScript while a clicking of button it will select a seat and change its background color to green and at the same time the button value will be added to the text field and will toggle accordingly.
Issue: I am adding all the value to the text field using an array, which is successful but during toggling it cannot able to subtract the particular clicking button value from array.
Here I cannot able to use jQuery because this page is coming from a ajax-page load.
// JavaScript Document
var Cur_id;
var Cur_val;
function setId(id, value) {
Cur_id = id;
Cur_val = value;
var SeatVal = document.getElementById(id);
if (SeatVal.style.backgroundImage == "") {
SeatVal.style.backgroundImage = "url(\'themes/frontend/images/greenseat.png\')";
var txbtElementSeat = new Array(document.getElementById("selectedseat").value += Cur_val + ",");
} else if (SeatVal.style.backgroundImage == 'url("themes/frontend/images/greenseat.png")') {
SeatVal.style.backgroundImage = "url(\'themes/frontend/images/seat.png\')";
var txbtElementSeatnbg = document.getElementById("selectedseat").value;
removeSeat(txbtElementSeatnbg, Cur_val);
function removeSeat(txbtElementSeatnbg, value) {
for (var i = 0; i <= txbtElementSeatnbg.length; i++) {
if (txbtElementSeatnbg[i] == value) {
txbtElementSeatnbg.splice(i, 1);
break;
}
}
}
} else if (SeatVal.style.backgroundImage == 'url("themes/frontend/images/seat.png")') {
SeatVal.style.backgroundImage = "url(\'themes/frontend/images/greenseat.png\')";
var txbtElementseatnb = document.getElementById("selectedseat").value += Cur_val + ",";
}
}
Your main issue seems to be that you try to save an array into a textfield. That will actually work, but will convert the array to a string representation.
var a = document.getElementById('selectedseat').value; therefore loads the string representation of the array into a variable "a", not the array itself!
Why don't you use a variable in the outer context (not the local function scope of setId()!) to hold the array? Maybe somewhat like this:
// Create a variable for the array!
var selectedSeats = new Array();
// Build a function that will update the textfield.
// Call this, whenever the array gets changed!
function updateListOfSelectedSeats() {
document.getElementById('selectedseat').value = selectedSeats.join(',');
}
// Removes a seat from the list of selected seats
function removeSeatFromList(seat) {
for (var i = 0; i < selectedSeats.length; i++) {
if (selectedSeats[i] == seat) {
selectedSeats.splice(i, 1);
updateListOfSelectedSeats();
break;
}
}
}
// Now the function that reacts to clicks on a seat
function setId(id, value) {
var Seat = document.getElementById(id);
switch (Seat.style.backgroundImage) {
case 'url("themes/frontend/images/greenseat.png")':
// Seat is already selected and needs to be deselected
Seat.style.backgroundImage = 'url("themes/frontend/images/seat.png")';
removeSeatFromList(value);
break;
case '':
case 'url("themes/frontend/images/seat.png")':
// Seat is empty, select it!
Seat.style.backgroundImage = 'url("themes/frontend/images/greenseat.png")';
selectedSeats.push(value);
updateListOfSelectedSeats();
break;
}
}
To remove the seat from the list use this
//remove seat from list
function removeSeat(seatListElm, seatValue) {
var arr=seatListElm.value.split(',');
var p=arr.indexOf(seatValue);
if(p!=-1){
arr.splice(p, 1);
seatListElm.value=arr.join(',');
}
}
seatListElm would be the element that hold "b5,c7,d5,c2"
seatValue would be something like this "c7"
Working demo code: JSFIDDLE