how to let jquery select2 disable one option dynamically? - javascript

I have some multiselect and i use jquery select2.I want to disable one option in other multiselect when this option is selected in one multiselect.
i write this code,but it does work.
$("select.multiselect").on("change", function(e) {
if(e.added){
for(var i=0;i<this.options.length;i++){
var vals = $(this).select2("val");
for(var j=0;j<vals.length;j++){
if(this.options[i].value===vals[j]){
this.options[i].selected=true;
}
}
};
}
if(e.removed){
for(var i=0;i<this.options.length;i++){
if(this.options[i].value===e.removed.id){
this.options[i].selected=false;
}
};
}
});
how to do it?

It was more complicated then I thought but here is what I came up with:
$('select.multiselect').on('change', function(e) {
// the selected values
var vals = $(this).select2("val");
// selects contains all the OTHER select forms
var selects = $('select').not('#'+$(this).attr('id'));
// loop trough all the selects
for (var i = 0; i < selects.length; i++) {
//re-enable all options before
$(selects[i]).find('option').removeAttr('disabled');
// loop trough all the values
for (var j = 0; j < vals.length; j++) {
// disabled attribute
$(selects[i]).find('option[value='+vals[j]+']').attr('disabled', 'disabled');
}
}
});
Here's a fiddle if you want to see the result in action
Make sure all your select elements have a unique id.

Related

javascript :- get all inputs from webpage and print

I'm trying to get all inputs from the webpage and to print when the user click on the input field. I want when the user focuses on the input field to type print
You have to apply onfocus on individual inputs. You are not using the index i at all.
Do this:
var inputs = document.getElementsByTagName('input');
for (var i = 0; i < inputs.length; ++i) {
inputs[i].onfocus = function() {
console.log("focus");
};
}
Easier if you can use jQuery:
$('input').focus(function(){console.log('Focus')});
Your code is almost correct. Just add [i] as done in the code below. That way your onfocus targets each input individually.
var inputs = document.getElementsByTagName('input');
for (var i = 0; i < inputs.length; ++i) {
inputs[i].onfocus = function() {
console.log("focus");
};
}

How to keep checkbox state in google visualisation table with checkboxes

I am using google visualisation table and adding check boxes in the list. I want to select some rows with check boxes and perform some action on those selected row. But when the sort or page event is called the table is redrawn and the check boxes goes unchecked.
Here is the fiddle
How can I keep the checkbox state after the table is sorted or page is changed?
Thank you
Before the event is called, you can do something like this to save the checked state of you checkboxes:
var checkboxes = document.querySelectorAll("#table_div input[type=checkbox");
var checkboxesState = {};
for (var i = 0; i < checkboxes.length; i++) {
checkboxes[i].addEventListener("change", function(){
checkboxesState[this.getAttribute("id")] = this.checked;
});
}
And after the event is called, restore it:
google.visualization.events.addListener(table, 'sort', function(ev) {
//Needed, since the whole table DOM will change
checkboxes = document.querySelectorAll("#table_div input[type=checkbox");
for (var i = 0; i < checkboxes.length; i++) {
if (checkboxesState[checkboxes[i].getAttribute("id")]){
checkboxes[i].checked = checkboxesState[checkboxes[i].getAttribute("id")];
}
}
});

How to append select-options from multi-dimension array?

jsfiddle
HTML:
<select class="s1"></select>
<select class="s2"></select>
JS:
var test = [
["a","bsafd","cfsaf"],
["b","cvxb","cfsf"],
["c","hjymb","cfsaf"],
["d","vhthb","fsfc","fasfsa"],
["e","fsdb","fsfac"],
["f","zxczb","vcxc","fsafsd"],
["g","yjhdb","bvcbc"],
["h","vbnvb","yutkfc"],
["i","nbcvnb","ndnfgnmc"],
["j","ikgnb","ncnc"],
["k","fgncb","kjuc"]
];
$(function(){
for(var i=0;i<test.length;i++){
$(".s1").append("<option>"+test[i][0]+"</option>");
}
$(".s1").on("change", function(){
var value = $(this).val();
for(var i=0;i<test.length;i++){
if(test[i].indexOf(value)){
for(var j=0;j<test[i].length;i++){
$(".s2").append("<option>"+test[i][j]+"</option>");
}
}
}
});
});
I can get the first value from array test and append to the first select area. But I stacked on the second step. I want to append values to the second select area according to the user selection.
Fon instance, user select "a". The next two values should be append to the second area from the sub array which lead with "a".
Could someone tell me what am I done wrong and how to finish it?
Try the below code [check the inline comments where you did mistake],
$(function(){
for(var i=0;i<test.length;i++){
$(".s1").append("<option value='"+test[i][0]+"'>"+test[i][0]+"</option>");
// -----------------^ add value to all options
}
$(".s1").on("change", function(){
var value = $(this).val();
$(".s2").html('');// first make the second drop down blank
for(var i=0;i<test.length;i++){
if(test[i][0]==value){
for(var j=0,l=test[i].length;j<l;j++){
//----------------^ j++ not i++
$(".s2").append("<option>"+test[i][j]+"</option>");
}
}
}
});
});
Live Demo
Alternatively, if you make your json as key-value pair to differentiate the data for different drop down then it would more simpler to use it like,
// json where keys are used fro first drop down and its values are used for second one
var test = {
"a":["bsafd","cfsaf"],
"b":["cvxb","cfsf"],
"c":["hjymb","cfsaf"],
"d":["vhthb","fsfc","fasfsa"],
"e":["fsdb","fsfac"],
"f":["zxczb","vcxc","fsafsd"],
"g":["yjhdb","bvcbc"],
"h":["vbnvb","yutkfc"],
"i":["nbcvnb","ndnfgnmc"],
"j":["ikgnb","ncnc"],
"k":["fgncb","kjuc"]
};
$(function(){
$.each(test,function(i,v){
// store all keys to first drop down
$(".s1").append("<option value='"+i+"'>"+i+"</option>");
});
$(".s1").on("change", function(){
var value = this.value;
$('.s2').html('');
if(value){
// get the value for the key which is selected
$(test[value]).each(function(key,data){
$(".s2").append("<option value='"+data+"'>"+data+"</option>");
});
}
});
});
Working Demo
$(".s1").on("change", function(){
var value = $(this).val();
var option = '';
for(var i=0;i<test.length;i++){
/* Checking for first index */
if(test[i][0] == value){
for(var j = 1;j<test[i].length;j++){
/* creating options */
option += '<option>'+test[i][j]+'</option>';
}
}
}
/* remove previous options and prepend new option by selection */
$(".s2").empty().prepend(option);
});
Please try this..
check this fiddle
for(var i=0;i<test.length;i++){
if(test[i][0]==value){
(var j=1;j<test[i].length;j++){
$(".s2").append("<option>"+test[i][j]+"</option>");
}
}
}
It is not a multi-dimension array, so you need to loop through or filter() the original array to find the matching row and then add the elements of that array starting from 1 instead of 0 to ignore the "key" value:
$(function(){
for(var i=0;i<test.length;i++){
$(".s1").append("<option>"+test[i][0]+"</option>");
}
$(".s1").on("change", function(){
var value = $(this).val();
// find the first array which starts with value
var arr = test.filter(function(v){
return v[0] == value;
})[0];
// store a reference to .s2 so you don;t need to find it every time
var s2 = $(".s2");
// remove previous options
s2.empty();
for(var i = 1; i < arr.length; i++){
s2.append("<option>"+arr[i]+"</option>");
}
});
});
Updated Fiddle

How Can I Check the checkbox that belongs a GridVIew?

I want to do a javascript function that check the unchecked checkbox. My function nowadays, check all the unchecked checkbox, and I need that just check a specific GridView unchecked checkbox
function checar() {
var el = document.getElementsByTagName("input");
for (var i = 0; i < el.length; i++) {
if (el[i].type == "checkbox") {
el[i].checked = true;
}
}
}
You want to first limit the scope of your search for elements. One way to do so would be to use getElementById
function checar() {
var grd = document.getElementById("<%=grd.ClientID%>"); // <-- Add this line
var el = grd.getElementsByTagName("input"); // <-- change the scope of this to grd
//rest of your code here.
}
Sample using divs, but you'll get the idea I think: http://jsfiddle.net/8LRkk/
Edited to include setting the specific Grid ID.
To get at all of the checkboxes of a particular gridview, you need to grab checkboxes whose ClientID contain the portion of the gridview's ClientID as well since all controls have an id which is "stacked".
Your function should work as a base, it just needs to have an added check in it:
function checar() {
var el = document.getElementsByTagName("input");
// Get the client id of the gridview from ASP here
var gvID = '<%= this.myGridview.ClientID %>';
for (var i = 0; i < el.length; i++) {
// Call the id of the checkbox and check to see if it
// contains the client id of the gridview at the same time
if (el[i].type == "checkbox" && el.id.indexOf(gvID) != -1) {
el[i].checked = true;
}
}
}

how can I disable everything inside a form using javascript/jquery?

I have a form that pop up inside a layer, and I need to make everything inside that form read only regarding what type of input it is. Anyway to do so?
This is quite simple in plain JavaScript and will work efficiently in all browsers that support read-only form inputs (which is pretty much all browsers released in the last decade):
var form = document.getElementById("your_form_id");
var elements = form.elements;
for (var i = 0, len = elements.length; i < len; ++i) {
elements[i].readOnly = true;
}
With HTML5 it's possible to disable all inputs contained using the <fieldset disabled /> attribute.
disabled:
If this Boolean attribute is set, the form controls that are its
descendants, except descendants of its first optional
element, are disabled, i.e., not editable. They won't received any
browsing events, like mouse clicks or focus-related ones. Often
browsers display such controls as gray.
Reference: MDC: fieldset
You can use the :input selector, and do this:
$("#myForm :input").prop('readonly', true);
:input selects all <input>, <select>, <textarea> and <button> elements. Also the attribute is readonly, if you use disabled to the elements they won't be posted to the server, so choose which property you want based on that.
Its Pure Javascript :
var fields = document.getElementById("YOURDIVID").getElementsByTagName('*');
for(var i = 0; i < fields.length; i++)
{
fields[i].disabled = true;
}
Old question, but nobody mentioned using css:
pointer-events: none;
Whole form becomes immune from click but also hovers.
You can do this the easiest way by using jQuery. It will do this for all input, select and textarea elements (even if there are more than one in numbers of these types).
$("input, select, option, textarea", "#formid").prop('disabled',true);
or you can do this as well but this will disable all elements (only those elements on which it can be applied).
$("*", "#formid").prop('disabled',true);
disabled property can applies to following elements:
button
fieldset
input
optgroup
option
select
textarea
But its upto you that what do you prefer to use.
Old question, but right now you can do it easily in pure javascript with an array method:
form = document.querySelector('form-selector');
Array.from(form.elements).forEach(formElement => formElement.disabled = true);
1) form.elements returns a collection with all the form controls (inputs, buttons, fieldsets, etc.) as an HTMLFormControlsCollection.
2) Array.from() turns the collection into an array object.
3) This allows us to use the array.forEach() method to iterate through all the items in the array...
4) ...and disable them with formElement.disabled = true.
$("#formid input, #formid select").attr('disabled',true);
or to make it read-only:
$("#formid input, #formid select").attr('readonly',true);
Here is another pure JavaScript example that I used. Works fine without Array.from() as a NodeList has it's own forEach method.
document.querySelectorAll('#formID input, #formID select, #formID button, #formID textarea').forEach(elem => elem.disabled = true);
// get the reference to your form
// you may need to modify the following block of code, if you are not using ASP.NET forms
var theForm = document.forms['aspnetForm'];
if (!theForm) {
theForm = document.aspnetForm;
}
// this code disables all form elements
var elements = theForm.elements;
for (var i = 0, len = elements.length; i < len; ++i) {
elements[i].disabled = true;
}
This one has never failed me and I did not see this approach on the other answers.
//disable inputs
$.each($("#yourForm").find("input, button, textarea, select"), function(index, value) {
$(value).prop("disabled",true);
});
disable the form by setting an attribute on it that disables interaction generally
<style>form[busy]{pointer-events:none;}</style>
<form>....</form>
<script>
function submitting(event){
event.preventDefault();
const form = this; // or event.target;
// just in case...
if(form.hasAttribute('busy')) return;
// possibly do validation, etc... then disable if all good
form.setAttribute('busy','');
return fetch('/api/TODO', {/*TODO*/})
.then(result=>{ 'TODO show success' return result; })
.catch(error=>{ 'TODO show error info' return Promise.reject(error); })
.finally(()=>{
form.removeAttribute('busy');
})
;
}
Array.from(document.querySelectorAll('form')).forEach(form=>form.addEventListener('submit',submitting);
</script>
Javascript : Disable all form fields :
function disabledForm(){
var inputs = document.getElementsByTagName("input");
for (var i = 0; i < inputs.length; i++) {
inputs[i].disabled = true;
}
var selects = document.getElementsByTagName("select");
for (var i = 0; i < selects.length; i++) {
selects[i].disabled = true;
}
var textareas = document.getElementsByTagName("textarea");
for (var i = 0; i < textareas.length; i++) {
textareas[i].disabled = true;
}
var buttons = document.getElementsByTagName("button");
for (var i = 0; i < buttons.length; i++) {
buttons[i].disabled = true;
}
}
To Enabled all fields of form see below code
function enableForm(){
var inputs = document.getElementsByTagName("input");
for (var i = 0; i < inputs.length; i++) {
inputs[i].disabled = false;
}
var selects = document.getElementsByTagName("select");
for (var i = 0; i < selects.length; i++) {
selects[i].disabled = false;
}
var textareas = document.getElementsByTagName("textarea");
for (var i = 0; i < textareas.length; i++) {
textareas[i].disabled = false;
}
var buttons = document.getElementsByTagName("button");
for (var i = 0; i < buttons.length; i++) {
buttons[i].disabled = false;
}
}
As the answer by Tim Down I suggest:
const FORM_ELEMENTS = document.getElementById('idelementhere').elements;
for (i = 0; i < FORM_ELEMENTS.length; i++) {
FORM_ELEMENTS[i].disabled = true;
}
This will disable all elements inside a form.
for what it is worth, knowing that this post is VERY old... This is NOT a read-only approach, but works for me. I use form.hidden = true.
Thanks Tim,
That was really helpful.
I have done a little tweaking when we have controls and we handle a event on them.
var form = document.getElementById("form");
var elements = form.elements;
for (var i = 0, len = elements.length; i < len; ++i) {
elements[i].setAttribute("onmousedown", "");
}

Categories