Changing class of html element using Javascript and string interpolation - javascript

I have a HTML element with the id of "bigOne". Its size is determined by its class and the associated CSS. The class names are "p1", "p2", "p3", etc, all the way up to "p100".
One the page is an input and a button. I am trying to create a function so that when a number is typed in the input and the button clicked that the class of the "bigOne" is changed to the corresponding number, e.g. when 80 is entered and the button clicked the class changed from "p50" to "p80". In my code below I have been able to create this exact scenario but what I want to be able to do is be able to type in any number and change the class appropriately, e.g. submitting 4 creates the class p4 or submitting 99 creates the class p99. This is where I have come completely stuck.
Im am sure there isn't too much code required but I just can not get it.
<div id="options">
<label></label>
<input id="changes" />
<button id="myButton">Submit</button>
</div>
<script type="text/javascript">
document.getElementById("myButton").onclick=function() {
if (document.getElementById("changes").value=="80") {
document.getElementById("bigOne").classList.contains('p50');
document.getElementById("bigOne").classList.toggle('p80');
}
}
</script>

Since you tag your question with jquery... :
<script>
$(function(){
$('#myButton').click(function(){
$('#bigOne').removeClass(); //to clean old classes
//we get the value from the input and add the p class
$('#bigOne').addClass('p'+$('#changes').val());
});
});
</script>

I suggest that you fetch the value of the element where the number is put in, and store it into the string below called "theNewClassName":
var theNewClassName = document.getElementById("elementToTakeValueFrom").innerHTML;
document.getElementById("elementToGiveClassTo").className = theNewClassName;
//or whatever classname you wanted it to change to
Or
document.getElementById("bigOne").className = "blablabla";
You get the idea.

Related

Changing inner HTML of a button with dynamic id

On a project I'm working on, a HTML file is defining a Javascript template used on selection buttons. All buttons have a "Change..." label that I want to localize (set dynamically). In other cases I'm searching for the element ID and setting the InnerHTML accordingly. But in this case, the ID of the buttons are defined dynamically. Is it possible to have a text element inside the button element, search for this element, and set its InnerHTML value?
<script id="optionSelectionTemplate" type="text/x-handlebars-template">
<div class="sub-section option-selection">
{{#if name}}<h4>{{name}}</h4>{{/if}}
<div class="current"></div><button class="button" id="{{id}}" data-action-id="{{id}}">Change...</button>
</div>
</script>
I've been searching this for a while now. But given that my forte is not web development, I'm not really sure what to search for...
You may be able to get the button element(s) by its class instead; for example:
var x = document.getElementsByClassName("button");
As you suggested, you can improve your selection's precision by first getting the 'optionSelectionTemplate' element(s) like so:
var x = document.getElementById("optionSelectionTemplate").getElementsByClassName("button");
Or if you prefer:
var x = document.getElementById("optionSelectionTemplate").getElementsByTagName("button");
Here are some links for more on these method:
https://www.w3schools.com/jsref/met_document_getelementsbyclassname.asp
https://www.w3schools.com/jsref/met_document_getelementsbytagname.asp
Depending on how dynamic your localization should become, you could also specify the text inside a (locale-dependent) CSS as in https://jsfiddle.net/1gws5kat/ :
[HTML]
<button class="button btn_change" id="{{id}}" data-action-id="{{id}}"></button>
[CSS]
.btn_change:before { content: "Change..."; }
In particular when dealing with a large number of identically-named elements (i.e. many "Change" buttons), this might be pretty handy.
You find those btns by this command:
var btnlist= $(':button')
This Camano get you all button in your html file, then loop ton in and apply your changing.
Before call this command, jquery must be install.

JQuery $(this).find("#id").text("text") not changing text

I'm looping through all elements of a certain class on a page and editing the text of an tag in that class with a certain id. I'm referencing the element with $(this).find('#time') and trying to change the text of that object using $(this).find('#time').text("test"), but the the text of the element isn't changing and I can't figure out why.
EDIT:
$('.box').each(function(i, obj){} This is what the loop is, the odd thing is that when i simply reference the text with $(this).find('#time').text() i receive the correct output. But the text won't change when using .text().
Here is the code im using to change the object text:
var time = response.substring(7, 15);
var user = response.substring(16, response.length);
$(this).find('#time').text(time);
$(this).find('#name').text(response.substring(user));
Game Page
<div class="box">
<h1>${{ game_object.amount }}</h1>
<h2 id="time">{{ game_object.start_time}}</h2>
<p id="name">{{ game_object.current_top_user }}</p>
CLICK NOW
</div>
Try to use .html
$(this).find('#time').html("test")
or maybe this can help you:
$('body').find('#time').text('test');
Because the ID of an element must to be unique

How to dynamically access user-entered Input-field-data, in Javascript or J-Query

HELP!!.... I can't dynamically access data entered by users into Input fields!
I'm a curriculum-designer trying to make a 'Matching'-activity (18-questions-with-18-scrambled-up-possible-answers), in which answer-choices get dynamically crossed out, 1 by 1, as they get 'used up' by the student, whenever (s)he types the letter of that choice (in this case "r") into the input-field. Here's the HTML for 1 of those 18 matches: (Hint: Pay attention to the "id"-attributes)
HTML
<input title="Question 18 - type 'R' into this input field"
class="questions" maxlength="1" id="18" onblur="My_Blur_Fx(this);">
</input>
<span class="r_as_selected, choices" id="r"> <!--I use the first class ('r_as_selected') in the J-Query example below, and the 2nd class ('choices') in the Javascript example below.-->
[Choice] R. (**All this span should soon be crossed-out.**)
</span>
I thought I could pull this off with a "change" event. However, neither my Javascript, nor my J-Query seems to be able to do it, because neither one can dynamically access the user's typed-in input (the very stuff that PHP would normally access via GET or POST).
J-Query
My J-Query-attempt to dynamically access this user-entered input...
$("input").change(function(){
$("input"[value="r"])
.add('.r_as_selected')
.eq(1).css({'color': 'red', 'text-decoration': 'line-through'})
});
...failed because, although it could cross out the '#r' answer-choice, yet it would ALSO cross it out whenever they typed in ANYTHING....So the [value='r'] part of the code wasn't able to target JUST the field where someone had typed 'r'.
Javascript
My Javascript-attempt to dynamically access this user-entered input...
<script>
function My_Blur_Fx(x) {
var userInput = document.getElementById(x).value;
var userChoices = document.getElementsByClassName("choices").id;
var i;
for(i = 0; i < 18; i++)
{ if (userChoices[i].attributes[1].value == userInput) {
/*Note: "attributes[1] is my way of accessing the 2nd attribute in the HTML span above, which is 'id="r"'*/
userChoices[i].style.textDecoration = "line-through";};
};
}
</script>
...failed too because an 'Input' is an "Element" whose "Value," is defined by the DOM to be "NULL,"...so line 3 above gives an error. Neither could any of the other potentially-relevant DOM-modifiers, instead of .value (i.e. .innerHTML / .nodeValue / .attributes) access that user-entered value. So it seems that 'Input' elements just can't be accessed dynamically. . . . ( Any suggestions...J-Query, Javascript, or other? )
You can't use an attribute selector to match user input, it only matches the static attributes, not the dynamic values. You can use .filter() to search for an element that matches a selector and has a specific value.
$("input").change(function() {
$("input").filter(function() {
return this.value == 'r';
}).add(".r_as_selected")
.eq(1).css({'color': 'red', 'text-decoration': 'line-through'});
});
You have several problems in MyBlurFx().
document.getElementById(x).value won't work beceause x is the element, not its ID. You should just use x.value.
document.getElementsByClassName("choices").id won't work because getElementsByClassName() returns a NodeList, not a single element, so it doesn't have an id property. But you don't need the ID, just use document.getElementsByClassName("choices"), since the for loop operates on the elements, not IDs.
Maybe there is more than one mistake, but I see that your code $("input"[value="r"]) is same as $(undefined). You must use $('input[value=\'r\']') instead.

Accessing Div, by class name, with javascript

I can not access this data within the div with javascript.
<div class="questions-text-alignment whiteTextWithShadow question-size-v4">
DATA HERE
</div>
Any suggestions?
Way 1
You can access the data using jQuery in the following way:
<script>
$(document).ready(function(){
var data = $(".questions-text-alignment").html();
alert(data);
})
</script>
Way 2
Without jQuery:
<script>
var data = document.getElementsByClassName("questions-text-alignment");
alert(data[0].innerHTML);
</script>
You can access using document.getElementsByClassName(), But the thing is you will get an array object. Using the array you have to find out yours. In the below sample I have assumed only one class available.
var arr = document.getElementsByClassName("question-size-v4");
alert(arr[0].innerHTML);
DEMO
You can try like this
<script>
function getHtml() {
var html = document.getElementsByClassName("questions-text-alignment")[0];
alert(html.innerHTML);
}
</script>
<div class="questions-text-alignment whiteTextWithShadow question-size-v4">
DATA HERE
</div>
<input type="button" name="click" value="click" onclick="getHtml()" />
You should Use Id to select element in this scenario -
DEMO
<script>
function changeData() {
document.getElementById('contentDiv').innerHTML= "Updated Content";
}
</script>
<body>
<div id="contentDiv">
Content Of My Div
</div> </br>
<input type = "button" onClick = "changeData()"
value = "change div text" />
</body>
#StevenTang I exactly got stuck on the same problem and here is my solution.
document.getElementsByClassName("question-size-4")
works fine on full HTML document load and only if you have a single DIV object identified by this class name.
Otherwise you get HTMLCollection object for preview via ChromeTools to be opened in your web browser.
To identify individual DIV object, including your Class name and Data Here use Firebug and select your Data and open in Firebug with right mouse click (submenu select).
Once your DIV object selected and identified to include your class name and your Data Here is opened in console.log (Chrome tools), clicking on HTMLCollection you get every DIV object identified by index (natural number) as in array.
Selecting the correct index (natural number), you can access your Data Here via
elements = document.getElementsByClassName("question-size-4");
DataHere = elements[correct DIV index].innerHTML or .innerText
You need to manipulate
x = elements.length;
first to know if any such DIV object identified by your class name really exists and has been downloaded.
If x = 0 it means HTMLCollection is empty and elements.innerHTML generates undefined string
If x = 1 there is exactly a single DIV identified by your class name, so
elements.innerHTML should work fine
If x > 1; you have got more DIV objects identified by your class name, so you needd to select the correct one from array data stracture, entering correct index, as above.
It took me months to study the problem and to find the correct answer.
thank you

Why are only some attributes updated from my javascript function?

I have a button script to change the buttons in a frame based on the page loaded in the main frame. The problem I'm experiencing is that while the background images, tabindex and text on the button (innerHTML) all change as expected, the onclick doesn't. It appears to completely ignore it. Here's the script I'm using:
function createbutton(btn_N, btn_I, btn_L, btn_D) // (Div Name, Tab Index, Button Text, Page To Load){
var btnN = top.frames['buttonbar'].document.getElementById(btn_N);
btnN.style.cssText = "display:block; cursor:pointer; padding-left:16px; padding-top:5px;";
btnN.onmouseover = function() {this.style.backgroundImage = "url('./osdimages/navBG_roll.png')";};
btnN.onmouseout = function() {this.style.backgroundImage = '';};
btnN.tabindex = btn_I;
btnN.innerHTML = btn_L;
btnN.onclick = btn_D;
}
The button call looks like this:
createbutton("button01", 1, "New Order/Browse", "parent.frames['content'].location.href='createorder/createorder.asp';");
There is a difference between attributes and properties.
The best example of this is as follows:
HTML: <input type="text" value="hello" id="test" />
Type something in the text box
document.getElementById('test').value is whatever you typed
document.getElementById('test').getAttribute("value") is whatever was in the HTML
Some attributes are directly mapped to properties and vice versa, but this is not always the case.
For instance, the onClick attribute takes a string that is then eval'd, but the onclick property takes a function. This is why your code isn't working.
Either pass a valid function, or use setAttribute.
You are setting onclick with a string, it needs a function to execute.
createbutton("button01", 1, "New Order/Browse", function(){ parent.frames['content'].location.href='createorder/createorder.asp'; });

Categories