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.
Related
Hello I'm trying to add a class to all of my elements on a webpage. The overall goal is to grab all the elements on a webpage and add in a class. The class containing a font size will be changed to hide a message.
I'm getting this error
Uncaught TypeError: Cannot set property 'innerHTML' of null
I've tried moving my script outside the body tag of my index.html but its still not working.
Another problem is I can't add a class to all of the IDs I'm selecting. I can add classes manually like
$("#iconLog").addClass("style"); //this works
but when I try to add a class like this
empTwo = "#" + temp; //where empTwo is a string that equals "#iconLog"
$("empTwo").addClass("style") //this does not work
I'll post my entire script below for reference
$(function() {
var hideMsg = "f";
var n = hideMsg.length;
var i;
var j;
var holder;
var hideHolder;
// on button click - hide msg
$('#btnHide').on('click', function() {
//grab all IDS ON WEBPAGE
var allElements = document.getElementsByTagName("*");
var allIds = [];
for (var i = 0, n = allElements.length; i < n; ++i) {
var el = allElements[i];
if (el.id) {
allIds.push(el.id);
}
}
//ERRORS HAPPENING IN THIS LOOP
for(var i = 0; i < allElements.length; ++i)
{
console.log(allIds[i]);
try{
var temp = document.getElementById(allIds[i]).id;
}
catch(err){
document.getElementById("*").innerHTML = err.message;
}
tempTwo = "#" + temp;
console.log(tempTwo);
//$("#iconLog").addClass("style") //this works
$("tempTwo").addClass("style"); //this does not work
}
for(i = 0; i < n; i++) {
//set var holder to first value of the message to hide
holder = hideMsg.charCodeAt(i);
for(j = 7; -1 < j; j--) {
//set hideHolder to holders value
hideHolder = holder;
//mask hideHolder to grab the first bit to hide
hideHolder = hideHolder & (1<<j);
//grab the first element ID
if(hideHolder === 0) {
// embed the bit
// bitwise &=
} else {
//embed the bit
// bitwise ^=
}
}
}
});
});
To add a class to all elements you don't need a for loop. Try this:
$("*").addClass("style");
Same for setting the inner html of all elements. Try this:
$("*").html("Html here");
Remove the double quotes from empTwo .You don't need quotes when you are passing a varible as a selector. The variable itself contains a string so you don't need the quotes.
empTwo = "#" + temp;
$(empTwo).addClass("style") //this will work
Try this:
$(empTwo).addClass("style")
Note: You used string instead of variable:
well,
try this...
You were passing the varibale in the quotos because of that instead of getting value to empTwo it was searching directly for "empTwo".
$(empTwo).addClass("style");
to get all element try this-
var allElements = = document.body.getElementsByTagName("*");
Hoping this will help you :)
empTwo = "#" + temp; //where empTwo is a string that equals "#iconLog"
$("empTwo").addClass("style") //this does not work
You made mistake in the second Line.
The variable empTwo already is in string format.
So all you need to do is
$(empTwo).addClass("style") //this works because empTwo returns "#iconLog"
My app dynamically creates and deleted new elements based on the + / - buttons.
Inside the dynamically created elements are text forms. I want whatever the user types into the text form to be displayed in another dynamically created element.
$('.LName').keyup(function(event) {
var crazy = {};
for (var x = 1; x < i; x++) {
crazy[x] = function() {
$('#sideChange'+ x).keyup(function(event) {
var value = $(this).val();
$('.sLoan'+ x).text(value);
})
}
}
for (var p = 1; p < i; p++) {
crazy[p]();
}
});
For example, I accomplished this for changing the text in the previous element by including the function in the html onkeyup attribute, but I don't know how to accurately target other elements.
var changeTitle = function() {
var loanTitle = $(this).val();
var code = $("input[type='text'][name='loanName']").keyCode || $("input[type='text'][name='loanName']").which;
var length = loanTitle.length;
console.log(length);
if(length < 1 || code == 8) {
$(this).prev().text('Loan');
}
else {
$(this).prev().text(loanTitle);
}
};
What youll probably want to do is data bind the two elements with some sort of ID you generate. In the fiddle below, I just use an incrementing number. When the keyup happens, I grab that elements data-id and use it to find its "mirrored" input.
$('.mirror[data-id="'+id+'"]').val(text);
Your question was a bit vague but I think this is what you were asking for.
http://jsfiddle.net/swoogie/f8cd4voz/
I dynamically create this list element and information a user has typed in shows up in it when a button is clicked 'info' is text and shuld show as it is but 'grade' is a number that i want to convert to another sign with the function changeNumber() but I am new to javascript and cant figure out how to make this function, can anyone give a suggestion or point me in the right direction?
var list = $("#filmlista");
var list_array = new Array();
function updateFilmList()
{
document.getElementById("name").value = '';
document.getElementById("star").value = 0;
var listan = list_array[0][0];
var grade = list_array[0][1];
var element = '<li class="lista">' + list + '<span class="grade">'+ changeNumber(grade) +'</span></li>';
list.append(element);
}
should I use innerHTML? not shure I understand how it works? and how do I use the replace method if I have to replace many different numbers to the amount of signs the number is?
for example if the number is 5 it should show up as: *****, if number is 3 show up as: *** and so on
Here's some code that should do the trick:
Add this function into your script.
function changeNumber(number) {
var finalProduct = "";
for (var i = 0; i < number; i++) {
finalProduct += "*";
}
return finalProduct;
}
Replace the updateFilmsList with this code.
document.getElementById("name").value = '';
document.getElementById("star").value = 0;
var listan = list_array[0][0];
var grade = changeNumber(list_array[0][1]);
var element = '<li class="lista">' + list + '<span class="grade">'+ grade +'</span></li>';
list.append(element);
It looks like you're trying to do something like PHP's str_repeat. In that case, take a look at str_repeat from PHPJS
There are options other than a loop:
function charString(n, c) {
n = n? ++n : 0;
return new Array(n).join(c);
}
charString(3, '*'); // ***
You can use innerHTML to set the text content of an element provided none of the text might be mistaken for markup. Otherwise, set the textContent (W3C compliant) or innerText (IE proprietary but widely implemented) property as appropriate.
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 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;
}