Altering the value of an option (select) element? - javascript

I'm attempting to select the selected value of a <select> form element, and append the value with -R. (This will be for regex matching later on). Anyway, so far I've tried the following:
Attempt 1:
var country = $('select[name=g_country\\['+value+'\\]]').val();
$('select[name=g_country\\['+value+'\\]]').find('option[value=' + value +']').val(country + '-R');
Attempt 2:
var country = $('select[name=g_country\\['+value+'\\]]').val();
$('select[name=g_country\\['+value+'\\]]').val(country + '-R');
I can tell that the selection of the correct form element (using delete_x, where x is a number) works fine, as the form elements to disable when .select-delete is clicked, however the value setting doesn't. The commented portion down the bottom is what I've been using to check the value of the <select> element post-value change (or what should be post-value change).
Here's a link to my jsFiddle: http://jsfiddle.net/gPF8X/11/
Any help/edits/answers will be greatly appreciated!

Try this:
$('.select-delete').click( function() {
var value = $(this).attr('id');
value = value.replace('delete_', '');
var country = $('select[name=g_country\\['+value+'\\]] option:selected').val() + '-R';
alert(country);
$('select[name=g_country\\['+value+'\\]] option:selected').val(country);
$('select[name=g_country\\['+value+'\\]]').attr('disabled','1');
$('input[name=g_url\\['+value+'\\]]').attr('disabled','1');
$(this).css('display', 'none');
var check = $('select[name=g_country\\['+value+'\\]]').val();
$('#test').append(check);
});
There is an issue with your HTML as well.

Finally came up with the right selector, props to #gjohn for the idea.
Here's my final working code, that appropriately adds -R to the end of g_country[x]:
$('.select-delete').click( function() {
var value = $(this).attr('id');
value = value.replace('delete_', '');
var country = $('select[name=g_country\\['+value+'\\]]').val();
$('select[name=g_country\\['+value+'\\]] > option:selected').val(country + '-R');
$('select[name=g_country\\['+value+'\\]]').attr('disabled','1');
$('input[name=g_url\\['+value+'\\]]').attr('disabled','1');
$(this).css('display', 'none');
});

Related

Updating id attribute using $(this) not working jquery

I'm using JQuery clone() method to clone form and updating form input value's "id" attribute increment by 1.
Everything is going perfect but I'm curious about $(this) and this.
In clone() -> each() method while updating input id I've faced issues like when I'm updating value like:
this.id=newId; then its working and updating id attribute
But if I use $(this).attr(oldId,newId) then its not working
If I use var old=newId then also its not working
I've referred this and this but still confused why last two methods are not working.
Full code:
var clonedTemplate = $(".form-section .row:first").clone();
var index = 0;
$("body").on('click', '.add', function () {
index++;
var formSection = clonedTemplate.clone().find(':input').each(function () {
var oldId = $(this).attr('id');
var newId = oldId + "_" + index;
this.id=newId; //its working and updating id attribute
$(this).attr(oldId,newId) // not working
oldId=newId; // not working
});
formSection.end().appendTo('.form-section');
});
Any help/suggestion or better solution would be appreciated.
you need to pass in the name of the attribute you are altering, not the value of it so this line
$(this).attr(oldId,newId)
needs to become
$(this).attr('id',newId)

How can I prevent users input to be cloned in the appended input box in javascript

When I insert some thing in the input box of module 1 and click add module button to clone the required elements that I need it clones also the inserted input I've tried to prevent that using event.preventDefault(); but it's still copying the input box with the inserted input from module 1 however, I can't clear it using the clear button that is located in the input box moreover the appended select options doesn't work and when I select an option it doesn't change.
Here is my demo of what's happening:-
http://jsfiddle.net/0ojjt9Lu/6/
and here is my javascript code:
$(document).ready(function(){
$("#Sadd").click(function(event) {
event.preventDefault();
var lastId = $("#modules h1").length;
var $newLabel = $("#module-1-label").clone();
var $newSc = $("#module-1-scredit").clone();
var $newSgrade = $("#module-1-sgrade").clone();
$newLabel.html("<h1>Module " + (lastId+1) + ":</h1>");
$newSc.find("label").attr("for", "Sc"+(lastId+1));
$newSc.find("input").attr("name", "Sc"+(lastId+1)).attr("id", "Sc"+(lastId+1));
$newSgrade.find("label").attr("for", "Sgrade"+(lastId+1));
$newSgrade.find("select").attr("name", "Sgrade"+(lastId+1)).attr("id", "Sgrade"+(lastId+1));
$("#modules").append($newLabel, $newSc, $newSgrade);
});
$("#Sremove").click(function() {
var lastId = $("#modules h1").length;
if(lastId > 5){
var lastLi = $("#modules h1").last().closest("li");
var lastLi2 = lastLi.next("li");
var lastLi3 = lastLi2.next("li");
lastLi.remove();
lastLi2.remove();
lastLi3.remove();
}
});
});
Use .val("") on the new input to clear the data in on the clone
or do $(clone).find('input').val(""); if there is more than one input
In your case with the select box you need to add the following lines
After you declare (or on the same line) the variables
var $newSc = $("#module-1-scredit").clone().find('input').val("");
var $newSgrade = $("#module-1-sgrade").clone().find('option:selected').removeAttr('selected');
$newSgrade.find('option[value="-1"]').attr('selected',true);
Edit: Had to handle the reselection of the select due to default value being "-1" however you may need to look at the cloning of this select element. Perhaps on the page have the blank question hidden and just clone that.

exchanging values in a select list with jQuery

I'm trying to swap select option values with jQuery when a links clicked, at the moment its just resetting the select when the links clicked, not sure what's going wrong?:
jQuery:
$(function () {
$("#swapCurrency").click(function (e) {
var selectOne = $("#currency-from").html();
var selectTwo = $("#currency-to").html();
$("#currency-from").html(selectTwo);
$("#currency-to").html(selectOne);
return false;
});
});
JS Fiddle here: http://jsfiddle.net/tchh2/
I wrote it in a step-by-step way so it is easier to understand:
$("#swapCurrency").click(function (e) {
//get the DOM elements for the selects, store them into variables
var selectOne = $("#currency-from");
var selectTwo = $("#currency-to");
//get all the direct children of the selects (option or optgroup elements)
//and remove them from the DOM but keep events and data (detach)
//and store them into variables
//after this, both selects will be empty
var childrenOne = selectOne.children().detach();
var childrenTwo = selectTwo.children().detach();
//put the children into their new home
childrenOne.appendTo(selectTwo);
childrenTwo.appendTo(selectOne);
return false;
});
jsFiddle Demo
Your approach works with transforming DOM elements to HTML and back. The problem is you lose important information this way, like which element was selected (it is stored in a DOM property, not an HTML attribute, it just gives the starting point).
children()
detach()
appendTo()
That happens because you remove all elements from both <select> fields and put them as new again. To make it working as expected you'd better move the actual elements as follows:
$("#swapCurrency").click(function(e) {
var options = $("#currency-from > option").detach();
$("#currency-to > option").appendTo("#currency-from");
$("#currency-to").append(options);
return false;
});
DEMO: http://jsfiddle.net/tchh2/2/
You are replacing the whole HTML (every option) within the <select>. As long as each select has the same amount of options and they correspond to each other, you can use the selected index property to swap them:
$("#swapCurrency").click(function (e) {
var selOne = document.getElementById('currency-from'),
selTwo = document.getElementById('currency-to');
var selectOne = selOne.selectedIndex;
var selectTwo = selTwo.selectedIndex;
selOne.selectedIndex = selectTwo;
selTwo.selectedIndex = selectOne;
return false;
});
JSFiddle

changing text for a selected option only when its in selected mode

I am not sure if I confused everyone with the above title. My problem is as follows.
I am using standard javascript (no jQuery) and HTML for my code. The requirement is that for the <select>...</select> menu, I have a dynamic list of varying length.
Now if the length of the option[selectedIndex].text > 43 characters, I want to change the option[selectecIndex] to a new text.
I am able to do this by calling
this.options[this.selectedIndex].text = "changed text";
in the onChange event which works fine. The issue here is once the user decides to change the selection, the dropdownlist is showing the pervious-selected-text with changed text. This needs to show the original list.
I am stumped! is there a simpler way to do this?
Any help would be great.
Thanks
You can store previous text value in some data attribute and use it to reset text back when necessary:
document.getElementById('test').onchange = function() {
var option = this.options[this.selectedIndex];
option.setAttribute('data-text', option.text);
option.text = "changed text";
// Reset texts for all other options but current
for (var i = this.options.length; i--; ) {
if (i == this.selectedIndex) continue;
var text = this.options[i].getAttribute('data-text');
if (text) this.options[i].text = text;
}
};
http://jsfiddle.net/kb7CW/
You can do it pretty simply with jquery. Here is a working fiddle: http://jsfiddle.net/kb7CW/1/
Here is the script for it also:
//check if the changed text option exists, if so, hide it
$("select").on('click', function(){
if($('option#changed').length > 0)
{
$("#changed").hide()
}
});
//bind on change
$("select").on('change', function(){
var val = $(":selected").val(); //get the value of the selected item
var text = $(':selected').html(); //get the text inside the option tag
$(":selected").removeAttr('selected'); //remove the selected item from the selectedIndex
if($("#changed").length <1) //if the changed option doesn't exist, create a new option with the text you want it to have (perhaps substring 43 would be right
$(this).append('<option id="changed" value =' + val + ' selected="selected">Changed Text</option>');
else
$('#changed').val(val) //if it already exists, change its value
$(this).prop('selectedIndex', $("#changed").prop('index')); //set the changed text option to selected;
});

jquery $(this).attr(…) returns undefined

I'm trying to get the title of an option element, but it keeps returning undefined. This also happens for $(this).attr("name")…and $(this).attr("value"), but curiously $(this).val() works (as expected). Yet, I'm able to set the value with $(this).attr("value", "baz").
Fiddle: http://jsfiddle.net/jshado1/JgAJC/1/
this points to the <select> element. For the selected option, use:
this.options[this.selectedIndex]
Full code (you can safely unwrap $opt's jquery wrapper, and use $opt.title and $opt.name, these are safe across all browsers):
$('select').change(function() {
var $opt = $(this.options[this.selectedIndex]),
t = $opt.attr("title"),
n = $opt.attr("name"),
v = this.value;
$("#name").text("name: "+n);
$("#title").text("title: "+n);
$("#value").text("value: "+v);
});
Another method, the jQuery-way is:
$('select').change(function() {
var $opt = $(this).children(':selected'),
t = $opt.attr("title"),
n = $opt.attr("name"),
v = this.value;
$("#name").text("name: "+n);
$("#title").text("title: "+n);
$("#value").text("value: "+v);
});
This is because you have mistaken what this represents in your code. The this represents the select element that has changed. Because the select node doesnt have a title attribute, it is undefined. What you would need to do is enumerate over the options list of the select and find the item that is selected. Then, you can operate on that item to find information like so:
var element = $(this.options[this.selectedIndex]);
element.attr('title');

Categories