jquery replicate values in to other area - javascript

IS there an easy way to replicate values in to other areas
i.e. if i have 2 or 3 select menus or other form fields.
say
<select id=first>
<option>1</option>
<option>2</option>
</select>
<select id=second>
<option>3</option>
<option>4</option>
</select>
<div id=firstvalue></div>
<div id=secondvalue></div>
If i want the divs html to automatically show the values of the select box, Would I have to do a piece of code for change on either component ?
Thanks
Lee

You want one code to work on both? Try this (example on jsFiddle)
$("select").change(function() // retrieve all `select` elements
{
// gets the corresponding `div`
$("div").eq($(this).index())
.html($(this).val()); // sets the html value of the `div` to
// the selected value on the `select` element
});
From jQuery docs:
Selectors
.change()
.eq()
.index()
.val()

If you want the divs to automatically show the selected value of any selectbox you can use the following jQuery:
$('#first').change(function(){
/* target the first selectbox with id #first and bind a change event to it */
$('#firstvalue').html($(this).val());
/* set the html of the div with id #firstvalue to the selected option*/
});
/* the same for the second selectbox */
$('#second').change(function(){
$('#secondvalue').html($(this).val());
});
I would recommend changing your HTML though, so the selectboxes that are being handled have the same class and store their target within a data attribute. Like so:
HTML
<select class="show_val" data-target="#value_1">
<option>1</option>
<option>2</option>
</select>
<div id="value_1"></div>
jQuery
$('.show_val').change(function(){
$($(this).data('target')).html($(this).val());
}
This way you can use the same jQuery event for all selectboxes.

You'd use the change event on the select box via the change or bind functions, and in the event handler you'd call the html or text function to set the text on the relevant div, getting the value of the selected option via val (your option elements don't have value attributes, so val will grab their text instead). In both cases, you look up the elements via the $ (or jQuery) function passing in a CSS selector (e.g., $("#first")) for the first select box.

You could do something like this so you wouldn't have to write code for each select/div:
$('select').change(function() {
$('div[id^="' + this.id + '"]').text($(this).val());
});
JSFiddle Example

You could also check out knockout.js and implement the MVVM (Model-View-View-Model) pattern, if you're using a JavaScript backing object that is bound to the view/page.

Related

Get element of select value

I have a HTML select drop down that is populated from a JQuery get request. You can view that here https://codepen.io/anon/pen/xjVjra
I am trying to get the following example element of the selected value on each change.
<small class="text-muted">ETH</small>
I have tried the following but that would just bring back the name of the selected option, which is not what I am after.
$(document).ready(function () {
$('#dropdown').on('change', function() {
alert( $(this).val()
});
});
Is it possible to drill to the inner code of the selected option and retrieve that data.
Thanks
I don't see how the question fits with the CodePen, but you could try something like this:
$("#cryptos :selected").attr("data-subtext");
I don't see any <small> tags in the HTML, as their shouldn't be because only <option> and <optgroup> are valid elements in a <select>.
If you meant <option>, you can use the :selected pseudo-class to get the actual <option> element instead of just its value:
// in select onchange where this == select element
$(this).find(':selected'); // the option element
Also, note that your CodePen example doesn't actually have the dropdown named #dropdown, so just make sure you use the appropriate selector.

How to get the text and value from a dropdown in Javascript

I have a very basic question. I want to select the SELECTED text and dropdown value from the dropdown and show in the alert box.
My attempt:
Dropdown
<p id="test">
Select a draft:
<select id="Select" name="Select">
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
</p>
JS
$("#Select").change(function()
{
alert($(this).val()); // IF THIS WORKS FINE THEN NEXT LINE CODE SHOULD WORK TOO
alert($(this).text()); // WHY THIS SHOWS ALL THE DROPDOWN TEXTS
alert($("#Select option:selected").text()); // THIS JUST WORKS FINE
});
Question 1: What $(this) signifies? If it's signifies selected element then it should show the text also when doing $(this).text(). BUT IT DOESN'T work as expected.
Question 2: If I need to select the value and text of the dropdown is above mentioned is the efficient way to go about it.
Please guide me.
My JSFIDDLE Attempt
In your change event handler, $(this) is the <select> element.
The element represented by $(this) depends on the context where it is used.
It usually is the element which triggered an event (like here), or the element targeted by the iteration of an .each() loop, for example.
When an <option> is selected, the <select> take its selected option value as a value...
It doesn't do it for the text of the selected option.
So that is why the second alert() statement doesn't work.
The keyword this in your example represents the element on which the event triggered. This means the select element. .text() return all text included in the element, so it gives all elements. .val() returns the value of an input, in this case it will return the value of the select, but beware as it does not return more than one value if you set mutiple=true.
Since we now know that .text() returns the text, and this is the input that changed, we can deduct that you'd prefer using .val() to get the value as it may differ from the display text.
alert($(this).find("option:selected").val());
$(this) is used to make the this object a JQuery object which includes some extra functionality.
You can try this if you want to get the selected item value and text:
$(this).find(":selected").val(); // Gets the value of the selected option, if the value attribute in the option element is null it will give you the text
$(this).find(":selected").text(); // Gets the text of the selected option
hi the 'this' part is the raw DOM element from javascript $(this) makes it a jquery object, so you can use jquery. In this case it's the select.
If I need to select the value and text of the dropdown is above mentioned is the efficient way to go about it.
Yes it's fine.
jQuery get specific option tag text
Answer to question 1:
$(this) means that you pass this to the $ function. In other words, you create a jQuery object from the this object. In your context, this refers to the elements matching the #Select selector: your select element.
$(this).text() is working normally because internally it calls innerText on the select tag: which contains the DOM code of your select and innerText contains all the text (not HTML) of the children of the select.
Answer to question 2:
To retreive the label of the selected option: $("#Select option:selected").text()
To retreive the value of the selected option: $("#Select option:selected").val()
You can alter what you already have written by changing this:
alert($(this).val() + $(this).text());
to:
alert($(this).val() + $("option:selected", this).text());
And overall giving you the code you already have.
$("#Select").change(function()
{
alert($(this).val() + $("option:selected", this).text());
alert($("#Select option:selected").text());
});
$(this) is just selecting the identified object that you are choosing to use 'change' on which in this case is the select box.
$("#Select").change(function() binds the function defined after this point to the HTML element <select id="Select" name="Select">. Therefore within that function, $(this) refers to that Select element. The information within that select element is: <option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>. This is why $(this).text() will give you all the options; you're asking for all the text inside that element.
($this).val() gets you the value of the overall select element, which is the text of the currently selected option.
this refers to the context which was used to invoke the function.
When you change the select option, this refers to the whole select dropdown.
If you look below, when I print the value of $(this).val, it gives the function which returns the value of the selected option.
Whereas, when I print the value of $(this).text, it gives the function which gives the whole select dropdown inner text.
To answer your second question, I think $(this).val() is more efficient as by using $(this) will always refer to the context which invokes the function. Thus, you can create modular code using it, by separating the use of anonymous function into a named function and using it for other select dropdown in your site, if you want in the future.
$("#Select").change(function()
{
console.log($(this).val);
console.log($(this).text);
console.log($(this).val()); // IF THIS WORKS FINE THEN NEXT LINE CODE SHOULD WORK TOO
console.log($(this).text()); // WHY THIS SHOWS ALL THE DROPDOWN TEXTS
console.log($("#Select option:selected").text()); // THIS JUST WORKS FINE
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="test">
Select a draft:
<select id="Select" name="Select">
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
</p>

Set focus on specific select box

I have multiple select boxes in the pages. I want to set focus on first element of specific select box. Here it shows how to set focus on select box. I need to say which one too. I tried below code but it didn't set the focus.
$('#thirdDropBox select:first').focus();
If you want the user to have focus on the first of multiple select's, you can use the following jQuery code:
If you have an id for the first select, you can directly access that element with the following:
$(document).ready(function () {
$('#idOfFirstSelect').focus();
});
However, if you don't have the id, the following code should work.
Demo: http://jsfiddle.net/biz79/1qo6mxnf/
$(document).ready(function () {
$('select').first().focus();
});
On a separate note, if you also want to have a default option selected, you can set that option to "selected" in the HTML:
<option value="saab" selected="selected">Saab</option>
The JQuery selector:
$('#thirdDropBox select:first')
will select the first "select" html element that is a descendant of an html-element that has an ID-attribute with the value "thirdDropBox".
For more information see: http://api.jquery.com/descendant-selector/
You probably need to remove the '#thirdDropBox"-part from your selector:
$('select:first')

Unable to call `change` event for cloned `select` control

I have dynamically added new row by clone the last row, this row contains select picker control.
How can I create the change event for newly added control.
I have tried by adding below script, but it does not work:
console.log($('#${field_uid}-resourcetypepicker-new_' + u).attr('value')); //prints value correctly.
//below event is not called.
$('#${field_uid}-resourcetypepicker-new_' + u).change(function() {
console.write('calling fine');
});
Below is the rendered HTML stuff, copied from Firebug:
<select id="customfield_11200-resourcetypepicker-new_3">
<option value="aaa">aaa</option>
<option value="ddd">ddd</option>
<option value="ddd">ddd</option>
</select>
Qhat can be the cause on this? Its IDs are also match in change and select both are customfield_11200-resourcetypepicker-new_3 same.
use on delegated event
$(document).on('change','#${field_uid}-resourcetypepicker-new_' + u,function() {
console.write('calling fine');
});
use closest static parent instead of document... for better performance

HTML form readonly SELECT tag/input

According to HTML specs, the select tag in HTML doesn't have a readonly attribute, only a disabled attribute. So if you want to keep the user from changing the dropdown, you have to use disabled.
The only problem is that disabled HTML form inputs don't get included in the POST / GET data.
What's the best way to emulate the readonly attribute for a select tag, and still get the POST data?
You should keep the select element disabled but also add another hidden input with the same name and value.
If you reenable your SELECT, you should copy its value to the hidden input in an onchange event and disable (or remove) the hidden input.
Here is a demo:
$('#mainform').submit(function() {
$('#formdata_container').show();
$('#formdata').html($(this).serialize());
return false;
});
$('#enableselect').click(function() {
$('#mainform input[name=animal]')
.attr("disabled", true);
$('#animal-select')
.attr('disabled', false)
.attr('name', 'animal');
$('#enableselect').hide();
return false;
});
#formdata_container {
padding: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<form id="mainform">
<select id="animal-select" disabled="true">
<option value="cat" selected>Cat</option>
<option value="dog">Dog</option>
<option value="hamster">Hamster</option>
</select>
<input type="hidden" name="animal" value="cat"/>
<button id="enableselect">Enable</button>
<select name="color">
<option value="blue" selected>Blue</option>
<option value="green">Green</option>
<option value="red">Red</option>
</select>
<input type="submit"/>
</form>
</div>
<div id="formdata_container" style="display:none">
<div>Submitted data:</div>
<div id="formdata">
</div>
</div>
We could also disable all except the selected option.
This way the dropdown still works (and submits its value) but the user can not select another value.
Demo
<select>
<option disabled>1</option>
<option selected>2</option>
<option disabled>3</option>
</select>
You can re-enable the select object on submit.
EDIT: i.e., normally disabling the select tag (with the disabled attribute) and then re-enabling it automatically just before submiting the form:
Example with jQuery:
To disable it:
$('#yourSelect').prop('disabled', true);
To re-enable it before submission so that GET / POST data is included:
$('#yourForm').on('submit', function() {
$('#yourSelect').prop('disabled', false);
});
In addition, you could re-enable every disabled input or select:
$('#yourForm').on('submit', function() {
$('input, select').prop('disabled', false);
});
another way of doing a readOnly attribute to a select element is by using css
you could do like :
$('#selection').css('pointer-events','none');
DEMO
Simple jQuery solution
Use this if your selects have the readonly class
jQuery('select.readonly option:not(:selected)').attr('disabled',true);
Or this if your selects have the readonly="readonly" attribute
$('select[readonly="readonly"] option:not(:selected)').attr('disabled',true);
<select id="countries" onfocus="this.defaultIndex=this.selectedIndex;" onchange="this.selectedIndex=this.defaultIndex;">
<option value="1">Country1</option>
<option value="2">Country2</option>
<option value="3">Country3</option>
<option value="4">Country4</option>
<option value="5">Country5</option>
<option value="6">Country6</option>
<option value="7" selected="selected">Country7</option>
<option value="8">Country8</option>
<option value="9">Country9</option>
</select>
Tested and working in IE 6, 7 & 8b2, Firefox 2 & 3, Opera 9.62, Safari 3.2.1 for Windows and Google Chrome.
I know that it is far too late, but it can be done with simple CSS:
select[readonly] option, select[readonly] optgroup {
display: none;
}
The style hides all the options and the groups when the select is in readonly state, so the user can not change his selection.
No JavaScript hacks are needed.
Simple CSS solution:
select[readonly]{
background: #eee;
cursor:no-drop;
}
select[readonly] option{
display:none;
}
This results in Select to be gray with nice "disable" cursor on hover
and on select the list of options is "empty" so you can not change its value.
Easier still:
add the style attribute to your select tag:
style="pointer-events: none;"
Yet another more contemporary option (no pun intended) is to disable all the options of the select element other then the selected one.
note however that this is an HTML 4.0 feature
and ie 6,7,8 beta 1 seem to not respect this.
http://www.gtalbot.org/BrowserBugsSection/MSIE7Bugs/OptionDisabledSupport.html
This is the best solution I have found:
$("#YourSELECTIdHere option:not(:selected)").prop("disabled", true);
The code above disables all other options not selected while keeping the selected option enabled. Doing so the selected option will make it into the post-back data.
A bit late to the party. But this seems to work flawlessly for me
select[readonly] {
pointer-events:none;
}
[SIMPLEST SOLUTION]
Since the OP specifically asked that he does not want to disable the select element, here is what i use to make a select readonly
In html
<select style="pointer-events: none;" onclick="return false;" onkeydown="return false;" ></select>
THAT's IT
Explanation
setting pointer-events to none disables the editing of the "select-element" with mouse/cursor events
setting the onclick & onkeydown functions to return false disables the editing of the "select-element" with keyboard
This way you don't have to create any extra element, or disable/re-enable the element with javascript or messing with form-submission logic, or use any third party library.
Plus you can easily add css-styling like setting backgrouns-color to grey or text color to grey to imply that element is readonly. I haven't added that to code, since that is pretty specific to your site-theme
Or if you want to do it via javascript
let isReadOnly = true ;
selectElement.onclick = function () {
return !isReadOnly ;
};
selectElement.onkeydown =function(){
return !isReadOnly ;
} ;
selectElement.style.pointerEvents = isReadOnly ? "none" : "all" ;
Set the select disabled when you plan for it to be read-only and then remove the disabled attribute just before submitting the form.
// global variable to store original event/handler for save button
var form_save_button_func = null;
// function to get jQuery object for save button
function get_form_button_by_id(button_id) {
return jQuery("input[type=button]#"+button_id);
}
// alter value of disabled element
function set_disabled_elem_value(elem_id, value) {
jQuery("#"+elem_id).removeAttr("disabled");
jQuery("#"+elem_id).val(value);
jQuery("#"+elem_id).attr('disabled','disabled');
}
function set_form_bottom_button_save_custom_code_generic(msg) {
// save original event/handler that was either declared
// through javascript or html onclick attribute
// in a global variable
form_save_button_func = get_form_button_by_id('BtnSave').prop('onclick'); // jQuery 1.6
//form_save_button_func = get_form_button_by_id('BtnSave').prop('onclick'); // jQuery 1.7
// unbind original event/handler (can use any of following statements below)
get_form_button_by_value('BtnSave').unbind('click');
get_form_button_by_value('BtnSave').removeAttr('onclick');
// alternate save code which also calls original event/handler stored in global variable
get_form_button_by_value('BtnSave').click(function(event){
event.preventDefault();
var confirm_result = confirm(msg);
if (confirm_result) {
if (jQuery("form.anyForm").find('input[type=text], textarea, select').filter(".disabled-form-elem").length > 0) {
jQuery("form.anyForm").find('input[type=text], textarea, select').filter(".disabled-form-elem").removeAttr("disabled");
}
// disallow further editing of fields once save operation is underway
// by making them readonly
// you can also disallow form editing by showing a large transparent
// div over form such as loading animation with "Saving" message text
jQuery("form.anyForm").find('input[type=text], textarea, select').attr('ReadOnly','True');
// now execute original event/handler
form_save_button_func();
}
});
}
$(document).ready(function() {
// if you want to define save button code in javascript then define it now
// code below for record update
set_form_bottom_button_save_custom_code_generic("Do you really want to update this record?");
// code below for new record
//set_form_bottom_button_save_custom_code_generic("Do you really want to create this new record?");
// start disabling elements on form load by also adding a class to identify disabled elements
jQuery("input[type=text]#phone").addClass('disabled-form-elem').attr('disabled','disabled');
jQuery("input[type=text]#fax").addClass('disabled-form-elem').attr('disabled','disabled');
jQuery("select#country").addClass('disabled-form-elem').attr('disabled','disabled');
jQuery("textarea#address").addClass('disabled-form-elem').attr('disabled','disabled');
set_disabled_elem_value('phone', '123121231');
set_disabled_elem_value('fax', '123123123');
set_disabled_elem_value('country', 'Pakistan');
set_disabled_elem_value('address', 'address');
}); // end of $(document).ready function
In addition to disabling the options that should not be selectable i wanted to actually make them dissapear from the list, but still be able to enable them should i need to later:
$("select[readonly]").find("option:not(:selected)").hide().attr("disabled",true);
This finds all select elements with a readonly attribute, then finds all options inside those selects that are not selected, then it hides them and disables them.
It is important to separate the jquery query in 2 for performance reasons, because jquery reads them from right to left, the code:
$("select[readonly] option:not(:selected)")
will first find all unselected options in the document and then filter those that are inside selects with a readonly attribute.
This is the simplest and best solution.
You will set a readolny attr on your select, or anyother attr like data-readonly, and do the following
$("select[readonly]").live("focus mousedown mouseup click",function(e){
e.preventDefault();
e.stopPropagation();
});
Solution with tabindex. Works with select but also text inputs.
Simply use a .disabled class.
CSS:
.disabled {
pointer-events:none; /* No cursor */
background-color: #eee; /* Gray background */
}
JS:
$(".disabled").attr("tabindex", "-1");
HTML:
<select class="disabled">
<option value="0">0</option>
</select>
<input type="text" class="disabled" />
Edit: With Internet Explorer, you also need this JS:
$(document).on("mousedown", ".disabled", function (e) {
e.preventDefault();
});
If you disable a form field, this won't be sent when form is submitted.
So if you need a readonly that works like disabled but sending values do this :
After any change in readonly properties of an element.
$('select.readonly option:not(:selected)').attr('disabled',true);
$('select:not([readonly]) option').removeAttr('disabled');
One simple server-side approach is to remove all the options except the one that you want to be selected. Thus, in Zend Framework 1.12, if $element is a Zend_Form_Element_Select:
$value = $element->getValue();
$options = $element->getAttrib('options');
$sole_option = array($value => $options[$value]);
$element->setAttrib('options', $sole_option);
Following on from Grant Wagners suggestion; here is a jQuery snippet that does it with handler functions instead of direct onXXX attributes:
var readonlySelect = function(selector, makeReadonly) {
$(selector).filter("select").each(function(i){
var select = $(this);
//remove any existing readonly handler
if(this.readonlyFn) select.unbind("change", this.readonlyFn);
if(this.readonlyIndex) this.readonlyIndex = null;
if(makeReadonly) {
this.readonlyIndex = this.selectedIndex;
this.readonlyFn = function(){
this.selectedIndex = this.readonlyIndex;
};
select.bind("change", this.readonlyFn);
}
});
};
What I found works great, with plain javascript (ie: no JQuery library required), is to change the innerHTML of the <select> tag to the desired single remaining value.
Before:
<select name='day' id='day'>
<option>SUN</option>
<option>MON</option>
<option>TUE</option>
<option>WED</option>
<option>THU</option>
<option>FRI</option>
<option>SAT</option>
</select>
Sample Javascript:
document.getElementById('day').innerHTML = '<option>FRI</option>';
After:
<select name='day' id='day'>
<option>FRI</option>
</select>
This way, no visiual effect change, and this will POST/GET within the <FORM>.
input being your <select> element:
input.querySelectorAll(':not([selected])').forEach(option => {
option.disabled = true
})
This will keep the select in the data (as it's not disabled) and only the option that are not selected are disabled, therefore not selectable.
The result is a readable select that cannot be changed (=> read only).
Rather than the select itself, you could disable all of the options except for the currently selected option. This gives the appearance of a working drop-down, but only the option you want passed in is a valid selection.
If the select dropdown is read-only since birth and does not need to change at all, perhaps you should use another control instead? Like a simple <div> (plus hidden form field) or an <input type="text">?
Added: If the dropdown is not read-only all the time and JavaScript is used to enable/disable it, then this is still a solution - just modify the DOM on-the-fly.
I resolved it with jquery:
$("select.myselect").bind("focus", function(){
if($(this).hasClass('readonly'))
{
$(this).blur();
return;
}
});
html solution:
<select onfocus="this.blur();">
javascript ones:
selectElement.addEventListener("focus", selectElement.blur, true);
selectElement.attachEvent("focus", selectElement.blur); //thanks, IE
to remove:
selectElement.removeEventListener("focus", selectElement.blur, true);
selectElement.detachEvent("focus", selectElement.blur); //thanks, IE
edit: added remove methods
In IE I was able to defeat the onfocus=>onblur approach by double-clicking.
But remembering the value and then restoring it in the onchange event seems to handle that issue.
<select onfocus="this.oldvalue=this.value;this.blur();" onchange="this.value=this.oldvalue;">
....
</select>
You can do similar without expando properties by using a javascript variable.
If you are using jquery validate, you can do the following below, I used the disabled attribute without a problem:
$(function(){
$('#myform').validate({
submitHandler:function(form){
$('select').removeAttr('disabled');
form.submit();
}
});
});
<select id="case_reason" name="case_reason" disabled="disabled">
disabled="disabled" ->will get your value from database dan show it in the form.
readonly="readonly" ->you can change your value in selectbox, but your value couldn't save in your database.
What's the best way to emulate the readonly attribute for a select
tag, and still get the POST data?
Just make it an input/text field and add the 'readonly' attribute to it. If the select is effectively 'disabled', then you can't change the value anyway, so you don't need the select tag, and you can simply display the "selected" value as a readonly text input. For most UI purposes I think this should suffice.

Categories