I've got a huge feeling I'm simply being idiotic here, but is it me or is Js not firing in JsFiddle?
I built this snippet here but can't seem to get it to fire. Im probably missing something super obvious, but would be grateful for any assistance.
HTML
<div id="col">
<h3 class="txt spacer">Dynamic input, based on select value...</h3>
<input type="text" name="field-one" class="txt stretch" />
<div class="boxes">
<input type="checkbox" id="box-2" onChange="myFunction()" checked>
<label for="box-2">Apply a name?</label>
</div>
</div>
</div>
Javascript
function myFunction() {
// Text field element.
var a = document.getElementByName('field-one');
// Checkbox element.
var b = document.getElementById('box-2');
if (b.checked) {
a.disabled = false;
a.placeholder = 'Not Applicable';
alert('Checkbox State Changed.');
} else {
a.disabled = true;
a.placeholder = 'Enter Your Full Name';
alert('Checkbox State Changed.');
}
}
JS FIDDLE
Thanks in advance for the assistance.
Regards,
-B.
EDIT
I'm an idiot. Thanks guys.
Couple of things here, it should be document.getElementsByTagName (plural) and you need to change the settings, that will embed the JS code in before the body closes.
var a = document.getElementsByName('field-one')[0];
I am using [0] here to access the very first element of the array as document.getElementsByName() will return you an array of elements if encountered multiple matching elements. If you want to select a specific one, make sure you select the DOM element in a more specific way.
And change the Load Type to
No wrap - in <body> (<head> will work as well)
Demo
The Javascript Load Type for your jsFiddle is set to onLoad. This will nest your myFunction function, and therefore won't be available in the global scope.
You can either change the Load Type, or set the variable on the window:
window.myFunction = function()....
NB: You then receive another error for getElementByName. This isn't a function of document. You're probably looking for getElementsByName.
Open the DevTools and you'll see
Uncaught ReferenceError: myFunction is not defined
at HTMLInputElement.onchange ((index):192)
Now why isn't the function defined? Perhaps it's not defined at the right spot?
Look at where you load your JavaScript and change it to:
Here's an updated fiddle. Note that I fixed a typo on line 3 getElementsByName.
First, set your seeting of javascript LOAD TYPE to head.
last, is getElementsByName not getElementByName and it would return array so you need to parse.
let a = document.getElementsByName('field-one')[0];
hope it's helpful.
Related
I want to use a value from a HTMl input but i cant make it into a variabel. Im a beginner at this so maybe it will be pretty obvious to you but i couldnt find anything on the internet that helped me with my problem.
script.js:
function getInputValue(){
var inputVal = document.getElementById("numberIn").value;
return inputVal;
}
document.getElementById('numberOut').innerHTML = getInputValue();
index.html:
<input type="text" placeholder="Dezimalzahl hier eingeben" id="numberIn">
<button type="button" onclick="getInputValue();">Convertieren</button>
<p id="numberOut"></p>
<script src="script.js"></script>
The reason it doesn't work for you is because the line document.getElementById('numberOut').innerHTML = getInputValue(); gets ran only once, when the input is empty. Your button's onclick only returns the value from the input, but it doesn't re-set it into numberOut.
Please look at my example, I took the same exact line and put it into a function that a button executes, and it seems to work perfectly!
function getInputValue() {
const inputValue = document.getElementById("myInput").value;
return inputValue;
}
function showValue() {
document.getElementById("result").innerHTML = getInputValue()
}
<input type="text" id="myInput"/>
<div id="result"></div>
<button onclick="showValue()">Click Me!</button>
Your idea is
When I click on the button, that's what should happen:
Read the value for an input element from the DOM.
Assign that value to another element.
but, in your implementation you did
When I click on the button:
Read the value.
Return it.
Believe me, that's what your implementation is saying.
If we came to the last step
document.getElementById('numberOut').innerHTML = getInputValue();
He's calling you, "Hey, why you are putting me outside the function, we did not agree like that".
So, that is the first correction
Let deal with the assignment function and place it inside the function.
The second, and after placed the assignment function in his reserved place ... the function now has the full steps
Read the value.
... ... ...
Assign it to the other element directly :), there is nothing that my function should return.
And, now!
Should I write the final getInputValue() function, or I let it to you?
Greetings ;)
I am a newbie to jquery.
I have this code written. I want to get the value of 'newValue' when the checkbox is checked. But this code returns 'undefined'.
Please can someone help to get the state of the checkbox: the return value should be true or false, 1 or 0.
$(tableCell).empty();
/Checkbox
$('<input type="checkbox" checked class="EditContactRow" style="width: 20%" />').appendTo($(tableCell)).val(controlValue).blur(function () {
var newValue = $(tableCell).find('checkbox').val();
.....
.....
}
Thanks
Ahoy, Olumide Omolayo
your code seems a little bit messy but it can be fixed for sure. Where is your HTML, would you please add it to your question?
If you need an example: if you have a checkbox you would take it's value by selecting it like this
var myCheckboxValue = $('#myCheckbox').val();
your code:
$('<input type="checkbox" checked class="EditContactRow" style="width: 20%" />')
will not work. since $() is used to access jQuery selectors, those SELECT an element in the HTML/DOM, then you do something with the element. (see this video)
If you want to ADD an element to the HTML/DOM you'd probably use something like
$("#myDiv").html('my html that will be added to the element with id="myDiv"');
Hope this helps. Feel free to ask more :)
P.S. If you post your full code here, we might able to help you much more than just write at random here. People might be able to actually give you the fixed version :)
just a small syntax error.
Change this line var newValue = $(tableCell).find('checkbox').val();
to
var newValue = $(tableCell).find('input[type="checkbox"]').val();
The problem was .find('checkbox') you are trying to find a element who's name is checkbox and you dont have one.. the attempt should be to find a element 's whos type is "checkbox" so use the syntax .find('input[type="checkbox"]')
Correct answer to my question from Reddy
var newValue = $(tableCell).find('input[type="checkbox"]').val();
Thank you all
Looked up several "Answers" to this problem, but it was mostly just people not treating the result returned by getElementsByName() as a NodeList!
Edit: I am trying to hide/show elements based on an element being clicked. I could hardcode this using document.getElementById and just add one everytime I have an element I want to hide/display. But it would be ideal if I could retrieve all elements named something and just run a loop on them to hide/show. Then I could just tag an element with a name when writing and this loop would work without alteration. Below my code is simply trying to popup an alert with the value for testing purposes. As for now, it consistently breaks with a null error. I am using and designing for internet explorer 9 as this is what the company uses.
Code:
<input type="radio" name="Area" value="Engineering" id="EngineeringCheck" onclick="javascript: ShowContentEngineering();" />Engineering
<script type="text/javascript">
function ShowContentEngineering() {
alert(document.getElementsByName('EngineeringAreas')[0].value)
document.getElementById('InformationBlock').style.display = 'block';
}
</script>
<h5 name="EngineeringAreas" value="luls"> WHAT THE HECK </h5>
Code above breaks saying that the object at getElementsByName('EngineeringAreas')[0] is null. Clearly, right below it, it is not null... Am I confusing getElementsByName('string')[0].value with the value of the element? Or is it retrieving some other value?
Ideally, I'd add other elements later, tag them with "EngineeringAreas" and never have to mess with the hide/show function.
Edit: Here is the error message:
Unhandled exception at line 53, column 9 in http://localhost:57264/Home/Index
0x800a138f - Microsoft JScript runtime error: Unable to get value of the property 'value': object is null or undefined
Here you go... seems:
onclick="javascript: <--- not necessary - just reference the function name
ShowContentEngineering needs to be set in the window context
You're referencing the "value" attribute of an element that doesn't allow value attributes (h5)
I made it work instead grabbing the innerHTML of the h5
Code
<input type="radio" name="Area" value="Engineering" id="EngineeringCheck" onclick="ShowContentEngineering();" />Engineering
<h5 name="EngineeringAreas"> WHAT THE HECK </h5>
<script>
window.ShowContentEngineering = function() {
alert(document.getElementsByName('EngineeringAreas')[0].innerHTML)
document.getElementById('InformationBlock').style.display = 'block';
}
</script>
Here's a working fiddle: https://jsfiddle.net/mu970a8k/
Insert .attributes[1] between .getElementsByName('EngineeringAreas') and .value. The 1 points to the second attribute in the <h5> element named EngineeringAreas, which is value. Placing .value after .attributes[1] should return the value text “luls” in the alert box. The alert code should then be set up like this:
alert(document.getElementsByName('EngineeringAreas')[0].attributes[1].value);
More Info: http://www.w3schools.com/jsref/prop_attr_value.asp
I'm looking to change the source attribute of an image element when my parent element is clicked. The child/image element is actually nested within two div's which complicates things slightly and I have a suspicion this is where i'm going wrong in my code.
The JavaScript is as follows:
<script src="js/jquery-1.7.2.min.js"></script>
<script>
$(document).ready(function () {
$('.slideContent').hide();
$('.slideHeader').toggle(
function () {
$(this).next('.slideContent').slideDown();
$(this).children('.dropDownIcon').children('img').src = "./images/dropDownIconUp.png";
},
function () {
$(this).next('.slideContent').fadeOut();
$(this).children('.dropDownIcon').children('img').src = "./images/dropDownIconDown.png";
}
); // end toggle
}); // end ready
And the HTML is:
<div class="slideHeader">
<div class="dropDownIcon">
<img class="dropDownClass" src="./images/dropDownIconDown.png"/>
</div>
<div>
<p>2014</p>
</div>
</div>
<div class="slideContent">
<div>
<p>2014</p>
</div>
</div>
The slideDown and fadeOut functions from jQuery work fine. However the image change does not happen. So i'm confident my eror is within the following code:
$(this).children('.dropDownIcon').children('img').src = "./images/dropDownIconUp.png";
But as far as I can see, I select the correct elements in my chain. If anyone can shine any light on this it would be much appreciated. As everything else on the internet verifys the code above should work (Whilst a be little messy).
Thanks in advance.
src is an attribute of the img tag, so use .attr()
Try,
$(this).children('.dropDownIcon').children('img').attr('src', "./images/dropDownIconUp.png");
instead of using children selector twice use $(this).find('img').attr('src','./images/dropDownIconUp.png')
I know you have accepted the answer but let me tell you some points in brief
.src = "blah" would not work for jquery objects.$() always returns a jquery object and you must use .attr() or .prop() to work with jquery objects
However jquery provides a simple way to convert to javascript object
if you still want to use as a javascript object you could it this way
$(".slideHeader").children('.dropDownIcon').children('img')[0].src = "./images/dropDownIconDown.png";
I try to set id4 in the following code:
<div id="id1">
<div id="id2">
<div id="id3">
<textarea id="id4"></textarea>
</div>
</div>
</div>
By using this code:
document.getElementById('id4').value = "...";
And this:
document.getElementById('id3').getElementsByTagName('textarea')[0].value = "...";
But nothing works.
UPDATED:
The textarea is replaced by CodeMirror editor. How do I set value to it?
Thanks a lot for the help!
The way to do this has changed slightly since the release of 3.0. It's now something like this:
var textArea = document.getElementById('myScript');
var editor = CodeMirror.fromTextArea(textArea);
editor.getDoc().setValue('var msg = "Hi";');
I like examples. Try this:
CodeMirror.fromTextArea(document.getElementById(id), {
lineNumbers: true
}).setValue("your code here");
As you said, the textarea is replaced by Codemirror. But it is replaced by an element with the class "CodeMirror". You can use querySelector to get the element. The current CodeMirror instance (and its methods) is attached to this element. So you can do:
document.querySelector('.CodeMirror').CodeMirror.setValue('VALUE')
CodeMirror ~4.6.0 you can do this, assuming you have a codemirror object:
var currentValue = myCodeMirrorObject.cm.getValue();
var str = 'some new value';
myCodeMirrorObject.cm.setValue(str);
The code you have should work. The most likely explanation for it failing is that the elements do not exist at the time you run it. If so the solutions are to either:
Move the JS so it appears after the elements have been created (e.g. to just before </body>)
Delay execution of the JS until the elements have been created (e.g. by moving it to a function that you assign as the onload event handler)
This has worked for my (pretty old) version of CodeMirror:
var editor=CodeMirror.fromTextArea('textarea_id');
editor.setCode('your string');