jQuery .on not firing - javascript

I have the following code (reproduced in this jsFiddle) that is not working. There are three options in the Type select box. If the first (True/False) is selected I need the first div to be shown, and if the second or third options are chosen then the second div needs to be shown. What is wrong with this code?
HTML:
<form name="editform">
Selector: <select class="selectors" name="1-type" id="1-type">
<option value="tf" selected="selected">True/False</option>
<option value="rd">Radio Button</option>
<option value="chk">Checkboxes</option>
</select>
<div id="seldiv-1">
Good Value: <select name="1-good_value" id="1-good_value">
<option value="true">True</option>
<option value="false">False</option>
</select>
</div>
<div id="textdiv-1" style="display:none;" disabled="disabled">
Good Value:
<textarea name="1-good_value" id="1-good_value"></textarea>
</div>
</form>
Javascript:
$(document).ready(function(){
$('.selectors').on('change',function (){
var arr = $(this).name.split("-");
var id = arr[0];
var val = $(this).val();
if(val=="tf") {
$('#textdiv-'+id).hide();
$('#seldiv'+id).show();
//Make textarea disabled
//Make selection enabled
} else {
$('#textdiv-'+id).hide();
$('#seldiv'+id).show();
//Disable selection
//Enable textarea
}
});
});

Uncaught TypeError: Cannot call method 'split' of undefined.
Change $(this).name.split("-"); to this.name.split("-");

it is not the on but the split function is giving you error, you are trying to get the name method of jquery object which is not available...either you need to use attr() to get the name from jquery object..or use this DOM object to get name
try this
var arr = $(this).attr('name').split("-");
or
var arr=this.name.split('_');
NOTE both your codes inside if/else condition is same.. so you won't notice the difference..check it out in your fiddle
working fiddle example

It 100% does fire, you have an error with $(this).name being undefined. I think what you actually wanted to do there was this.name
jQuery objects don't act just like DOMElement objects, i.e they don't have the same properties (like .name). Next time, open your web console when trying to find out why something doesn't work and you will catch most of your problems there.

This line is your problem:
var arr = $(this).name.split("-");
on is working properly but the line above is throwing an exception.
var arr = $(this).attr("name").split("-");
There are a few ways you could fix this, above is one example.

your problem is when trying to access $(this) which is undefined.
Try just this instead
this.name.split("-");

The name is not a valid property. Rather use id or change the way you access it to var arr = $(this).attr('name').split("-");.

Related

JsFiddle Javascript not firing?

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.

Increasing data attribute on click

What I'm attempting seems simple enough, but I'm obviously missing something. I have a simple select menu. After selecting a country, the value is passed into a variable, prepended with a hash to change it modify it to the respected id. Using this id I'm attempting to increase the data-size by 1. The only issue is that nothing happens with the data-size.
Here's a FIDDLE.
Things should flow like this:
Select country
Select value turned into id tag
data-size of said id is increased by 1 in the HTML
EDIT/UPDATE
I need the actual data-size value to be updated in the HTML because I have specific CSS that deals with different values.
HTML
<select name="countryList" id="countryList" class="selectBox">
<option value="" disabled selected>SELECT</option>
<option value="austria">Austria</option>
<option value="brazil">Brazil</option>
<option value="canada">Canada</option>
</select>
<button class="cancel">cancel</button>
<button class="confirm">confirm</button>
<div class="dot" data-size="0" id="austria"></div>
<div class="dot" data-size="0" id="brazil"></div>
<div class="dot" data-size="0" id="canada"></div>
jQuery
var countryPicked = "";
$('.confirm').on(touchClick, function(){
countryPicked = $('#countryList').val();
countryPicked = ($('#' + countryPicked));
var i = countryPicked.data('size');
countryPicked.data('size', i + 1);
});
Try changing touchClick to "click"
The DOM will not be changed visibly, because it is stored internally.
use attr('data-size',i + 1) if you want the DOM to be updated
Demo
Try doing
countryPicked.attr('data-size', i+1);
There seems to be something wrong with .data(), it can only READ the property, not SET it.
First of all please modify the handler to:
$('.confirm').on(`click`, function(){
//code here
});
For multiple events, give comma separated value as event.
Also note that changes will not be reflected in console. However you can check them using alert or console.log
Working Demo
jQuery stores the data internally if they don't exist the first time you set them. If you really want to force it:
countryPicked.attr('data-size', i + 1);
This works for me:
Fiddle: http://jsfiddle.net/GtT3Q/13/
$('.confirm').click(function(){
var countryPicked = $('#countryList').val();
countryPicked = $('#' + countryPicked);
var i = parseInt(countryPicked.attr('data-size'));
countryPicked.attr('data-size', i + 1);
});

Change href value with JS from select box

I have this select box that gets its data from my DB.
What I want to do is add Edit and Delete buttons next to my select box that will do the respective actions on the current selected option.
So I added two buttons that direct to php scripts that do all this work.
My problem is with JavaScript where I need to update the elements of the buttons.
However my JS function doesn't work.
It appears that it isn't even fired.
http://jsfiddle.net/y5g42/33/
HTML:
<select name='selectHotel' onChange='updateButtons(this.options[this.selectedIndex].text)'>
<option value="volvo.php">Volvo</option>
<option value="saab.php">Saab</option>
<option value="mercedes.php">Mercedes</option>
<option value="audi.php">Audi</option>
</select>
<a href='' id='editButton'><button>Edit</button></a>
<a href='' id='deleteButton'><button>Delete</button></a>
JavaScript:
function updateButtons(var) {
element = document.getElementById('editButton');
element.href = var;
}​
You can't use var as variable name - var is javascripts reserved word.
You have several problems with your logic and the fiddle itself.
Best way without using JavaScript library is to attach the onchange handler in the onload of the window and handle everything there:
window.onload = function() {
var oDDL = document.getElementById("selectHotel");
oDDL.onchange = function updateButtons() {
var oLink = document.getElementById('editButton');
oLink.href = oDDL.value;
};
oDDL.onchange();
};
To have it work, add id="selectHotel" to the <select> element and remove the inline onchange from it.
Updated fiddle.
In your initial fiddle you didn't choose proper framework properties.
Note that I am calling the onchange manually one time to reflect the selected value, otherwise clicking the button before selecting other value won't work.
jsFiddle's onLoad option wraps your code in a callback function.
Therefore, your function definition isn't visible outside the code.
You need to select No Wrap instead.
You just passed value rather than text on onchange function
onChange='updateButtons(this.options[this.selectedIndex].value)'
You can try something like this :
window.updateButtons = function(value) {
element = document.getElementById('editButton');
var url = window.location.href;
element.href = url + value;
console.log(element.href);
}
See Demo : http://jsfiddle.net/y5g42/46/

javascript and <option>

I do have the following JavaScript.
<form>
<select id="sel">
<option value="1">item_1</option>
<option value="2">item_2</option>
<option value="3">item_3</option>
</select>
<div id="show"></div>
</form>
<script type="text/javascript">
var sel = document.getElementById('sel');
sel.onchange = function() {
var show = document.getElementById('show');
show.innerHTML = this.value;
};
</script>
If I click onchange a new value (here: 1,2, or 3) is shown in the div "show". This is working fine. But my problem is that I want a different value to be shown but the value (1,2, or 3) should be submitted. The item has a unit like kg, pound, m, m², ....
I want something like that:
<option value="1" value2="kg">item_1</option>
I changed value to value2 in <script> but it didn't help.
show.innerHTML = this.value2;
How can I get it to work?
if you apply what #Simon said, you can try the following:
sel.onchange = function() {
var show = document.getElementById('show');
show.innerHTML = this.options[this.selectedIndex].getAttribute('value2');
}
Revised HTML:
<form>
<select id="sel">
<option value="1" data-unit="kg">item_1</option>
<option value="2" data-unit="kph">item_2</option>
<option value="3" data-unit="m2">item_3</option>
</select>
</form>
<div id="show"></div>
The revised HTML uses the custom, and in HTML5 valid, data-* attribute to store the units. I've also moved the div out of the form, but that's an entirely personal inclination, and one that you don't have to maintain (obviously...).
Amended JavaScript:
var sel = document.getElementById('sel');
sel.onchange = function() {
var show = document.getElementById('show');
show.innerHTML = this.value + this.options[this.selectedIndex].getAttribute('data-unit');
};
JS Fiddle demo.
The JavaScript looks for the option within the this node with the selectedIndex, and then uses getAttribute() to find the string contained within the data-unit attribute and concatenates that to the this.value string.
That should probably be:
show.innerHTML = this.options[this.selectedIndex].value;
If the list is not a dynamically generated one, why don't you use an "if else" construct or a "switch" construct on the populated values and display whatever you like?
Use the value attribute for the value you want submitted to the server since value is meant to contain a string that is meant to be interpreted by a computer as part of a form.
Use a different attribute to associate human readable text with the <option>. title and longdesc would be good choices.
I would recommend using jQuery if you can. If you're expecting to be able to use html5 compliant browsers, you can use the data attributes on your <option> elements. This way you'd be able to store whatever attributes you found useful.
jQuery data attributes usage
You can use .innerHTML instead of .value if you want to display the text from the drop down. If you want something completely different to be displayed, you'll need a lookup table or something similar - might be easier to use jQuery.

How to capture the text of an Select option?

So I have this:
<select id="list">
<option value="1">This is Me</option>
<option value="2">This is You</option>
<option value="3">And this is Mr. Nukem</option>
</select>
How would I go about grabbing the 'text' of the options here? The problem is, it needs to be 'dynamic', in the sense I need the text for the currently selected option...
I know a manual, static way of getting the text...
document.getElementById('list').options[1].text
That will grab "This is You"... But how do I get it for the currently selected option? Since I can't simply use:
document.getElementById('list').value
As that will grab the number... :-(
var list = document.getElementById('list');
var text = list.options[list.selectedIndex].text;
See (for example) here https://developer.mozilla.org/en/DOM/HTMLSelectElement
If you can use jQuery, you can try something like this:
$("#list").change(function() {
alert($(this).find("option[value=" + $(this).val() + "]").text());
});
See http://jsfiddle.net/MWu9f/ for a working example.
$("#list option[value='2']").text()
You can use this jQuery line and it will solve your problem.
In this an element with id list which has a property value equal to 2. What you want is the option child of the list.
The jQuery solution is like this:
$("#list option:selected").text()

Categories

Resources