calling a javascript function within markup created by javascript using Jquery - javascript

I have form fields which are displayed using Jquery on click of a button.
[select dropdown: conOperator] [textfield: conValue ] [select dropdown: conValuedd]
conValuedd is hidden by default.
I'm trying to figure out a way so that when I select either Apple or Banana in the first select drop down [conOperator], it hides the textfield conValue and displays drop down conValuedd instead. However, if I were to select Watermelon, it would display conValue and hide conValuedd again. Any ideas would be much appreciated.
$('<select id="conOperator' + num + '" name="conOperator' + num + '" class="standard_select" style="width:147px;">
<option>Watermelon</option>
<option>Apple</option>
<option>Banana</option>
</select>
<input type="text" id="conValue' + num + '" name="conValue' + num + '" class="short_input" value="" style="width:147px;">
<select style="display:none" id="conValuedd' + num +'" multiple="multiple" size="5">
<option value="option1">Blah</option>
<option value="option2">Blah</option>
</select>').appendTo('#addCondition');

Try something like a:
$('#addCondition').on('change','#conOperator' + num, function(e){
switch( $('option:checked',this).text() ){
case 'Apple':
case 'Banana':
$(this).nextAll(':text:first').hide();
$(this).nextAll('select:first').show();
break;
case 'Watermelon':
$(this).nextAll(':text:first').show();
$(this).nextAll('select:first').hide();
break;
}
});
$('#conOperator' + num).trigger('change');
DEMO

When you call appendTo(), the generated <select/> is added to the DOM so you can retrieve it with jQuery and add a listener on it.
$("#conOperator" + num).change(function() {
// Your logic here
}

Related

on change selects not working well

I`m trying to make a simple select which generate the next select box...
but I cant seem to make it work
so, as you can see I'm making divs that have ID and parent, when I'm clicking on the first select the value generate the next select box with the divs and the parent value.
this is the jQuery, but for some reason I cant understand why its not working.
$(document).ready(function() {
var i = 1;
var t = '#ss' + i;
$(t).change(function() {
i++;
t = '#ss' + i;
var pick = $(this).val();
$('#picks div').each(function() {
if ($(this).attr('parent') == pick) {
$('#ss' + i).append('<option value=' + $(this).text() + ' >' + $(this).text() + '</option>');
}
$('#ss' + i).removeAttr('disabled');
})
console.log(t);
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='picks'>
<div id='29' parent='26'>Pick1</div>
<div id='30' parent='29'>Pick11</div>
<div id='31' parent='26'>Pick</div>
</div>
<select id="ss1">
<option >First pick</option>
<option value="26">Angri</option>
<option value="27">lands</option>
<option value="28">tree</option>
</select>
<select id="ss2" disabled>
<option >Secound Pick</option>
</select>
<select id="ss3" disabled>
<option>Third Pick</option>
</select>
Here is a jsfiddle jsfiddle
Is this what you were shooting for? https://jsfiddle.net/6c5t8ort/
A couple things,
var t = '#ss' + i;
$(t).change(function() {
This only adds the change event to the first dropdown. If you give jQuery a selector (a class) if will add the event to all the elements though. Also the way you had your i variable set up means it would increment on every change.
The code below only attaches a change listener to the first ss ss1 so the change function is never called when you change ss2.
var i = 1;
var t = '#ss' + i;
$(t).change(function() {
You can fix this by adding a class on each select and using $(".myClass").change(function() {
or you can just attach the listener to all selects $("select").change(function() {
Also the value for the option tag does not include a "parent" number. In this case it would be Pick, Pick1, or Pick11.
$('#ss' + i).append('<option value=' + $(this).text() + ' >' + $(this).text() + '</option>');

Creating a select class dynamically

I'm struggling with modifying some code I have that dynamically creates a select box based on column values from a sharepoint list.
at the moment the code:
function getAjaxFilter(name, internalName) {
$.ajax({
url: $().SPServices.SPGetCurrentSite() + '/_layouts/filter.aspx?ListId=' + listID + '&FieldInternalName=' + internalName + '&ViewId=' + viewID + '&FilterOnly=1&Filter=1' + filterFieldsParams,
success: function(data) {
$('#filterField' + internalName).html(name).append($("<div></div>").append(data).find("select"));
//clear current onChange event
$("#diidFilter" + internalName).attr("onchange", '');
// add change event
$("#diidFilter" + internalName).change(function() {
FilterField(viewID, internalName, encodeURIComponent(this.options[this.selectedIndex].value), this.selectedIndex);
});
}
Creates the following html:
<div id="filterFieldSub_Category">
Sub Category
<select title="Filter by Sub_Category" id="diidFilterSub_Category">
<option>(All)</option>
<option>(Empty)</option>
<option value="Test">Test</option>
</select>
What I'm trying to achieve is to get it to produce a select class so I can apply it to a 3rd party selectbox styler like bootstrap select. so It needs to look like:
<select class="selectpicker" id= "filterFieldSub_Category">
<option>(all)</option>
<option>(empty)</option>
<option>test</option>
</select>
I'm not sure where to start, so if anyone could point me in the right direction that would be a huge help :)
You could add the class using addClass() :
$("#diidFilter" + internalName).addClass('selectpicker');
Hope this helps.

Trying to delete Select box using jQuery remove() function

I am trying to delete select box using jQuery remove function but it does not work. The select box itself is dynamically generated one. I want to delete the same select box if the user wants to delete the dropdown after adding. My code is:
$("#dltElement").click(function() {
$("#idSelect").remove();
});
My code to add the select boxes:
$(document).ready(function() {
var count = 3;
$("#btnCompare").click(function() {
if (count > 4) {
alert("Only 4 options are allowed");
return false;
}
$("#form-group").append(
"<select name='idSelect" + count + "' id='idSelect" + count + "'>" +
"<option>--Select Product" + counter + "--</option>" +
'<option value="p1">Product 1</option>' +
'<option value="p2">Product 2</option>' +
"</select>" + '<input type="button" value=" - " id="dltElement' + count + '" class="btn-minus pull-left" />'
);
count++;
}); // Script for adding dropdown dynamically
});
#idSelect is not present you have to use #idSelect0 or #idSelect1 ... and so on. Rather than you can lookup the events using event delegation on your #form-group to delete the closest element select closest to your input button or in your case your sibling select. This ~ is a sibling selector and will select the sibling select.
A good idea would be to add a class to your select and use that instead as we have used your class .btn-minus for listening to click events, (in case if you have more than one select all will be selected)
$("form-group").on('click', '.btn-minus' , function() {
$(this).find('~select').remove();
});
Find the sibling select and remove
Edit 2
I have added a snippet using .closest() You can check it out. Closest will try to locate the parent div with class container and remove the select and the minus button
$(document).ready(function() {
$("#form-group").on('click', '.btn-minus' , function() {
$(this).closest('.container').remove();
});
$("#btnCompare").click(function() {
var count = $("#form-group > div.container").length;
if (count >= 4) {
alert("Only 4 options are allowed");
return false;
}
//you need to have data-id="number" for all div.container, add class container and data-id to all the divs having select and button
var label = $("#form-group > div.container").last().data('id')*1+1;
$("#form-group").append(
"<div class=container data-id="+label+"><select name='idSelect" + label + "' id='idSelect" + label + "'>" +
"<option>--Select Product" + label + "--</option>" +
'<option value="p1">Product 1</option>' +
'<option value="p2">Product 2</option>' +
"</select>" + ' <input type="button" value=" - " id="dltElement' + label + '" class="btn-minus pull-left" /></div>'
);
}); // Script for adding dropdown dynamically
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="form-group">
<input type=button id=btnCompare value=btnCompare />
<div class="container" data-id="1">
<select id="idSelect1" name="idSelect1">
<option>--Select Product1--</option>
<option value="p1">Product 1</option>
<option value="p2">Product 2</option>
</select>
<input disabled type="button" class="btn-minus pull-left" id="dltElement1" value=" - ">
</div>
<div class="container" data-id="2">
<select id="idSelect2" name="idSelect2">
<option>--Select Product2--</option>
<option value="p1">Product 1</option>
<option value="p2">Product 2</option>
</select>
<input disabled type="button" class="btn-minus pull-left" id="dltElement2" value=" - ">
</div>
</div>
Edit 3:
Please find updated snippet. you need to have data-id="number" for all div.container, add class container and data-id to all the divs having select and button.
It is hard to have what you want since you can delete from the middle as well. You can have an array of deleted objects and update it everytime you delete or add into that. In this code I have added to disbaled input delete for 1 and 2 so that you can add and delete other 2. You can play around the logic.
It counts the number of divs in DOM and then checks if you are trying to add more than the limit, It then picks the last added in DOM and increments the data-id to use it as a label for the next select
Currently what you are using is called a "direct" binding which will only attach to element that exist on the page at the time your code makes the event binding call.
You need to use Event Delegation using .on() delegated-events approach, when generating elements dynamically or manipulation selector (like removing and adding classes).
i.e.
$(document).on('event','selector',callback_function)
Example
As you have defined CSS class, use the to get the select element and perform removal operation.
$("#form-group").on('click', ".btn-minus", function(){
$(this).prev('select').remove();
});
$.fn.prev()
Get the immediately preceding sibling of each element in the set of matched elements, optionally filtered by a selector.
you are assigning the <select> element an id that ends with a number, like this :
<select name='idSelect"+count+"' id='idSelect"+count+"'>
this means you end up with something like this :
<select name="idSelect1" id="idSelect1">
...
</select>
so the selector $("#idSelect") will never hit it unless it includes that number.
The part where you add the button :
'<input type="button" value=" - " id="dltElement' + count + '" class="btn-minus pull-left" />
has that same problem.
An easy way (though arguably not the best way) to achieve what you want is this :
function removeSelect(evt)
{
var selectBox = $(evt.currentTarget).parents(".group").find("select");
//do with select box as you will
}
$(document).ready(function() {
var count = 3;
$("#btnCompare").click(function() {
if (count > 4) {
alert("Only 4 options are allowed");
return false;
}
$("#form-group").append(
"<div class='group'>
"<select name='idSelect" + count + "' id='idSelect" + count + "'>" +
"<option>--Select Product" + counter + "--</option>" +
'<option value="p1">Product 1</option>' +
'<option value="p2">Product 2</option>' +
"</select>" + '<input type="button" value=" - " id="dltElement' + count + '" class="btn-minus pull-left" onclick="removeSelect(event)" /> </div>'
);
count++;
}); // Script for adding dropdown dynamically
});

User is able to add option to dropdown list by typing it in a text box

Is there any HTML/JavaScript code that can allow the viewer of a webpage to add a option to a dropdown select list by typing it in a text box???
Very basic example. No CSS, fancy formatting, error checking, anything. The value of the new option will be identical to the displayed string.
function newOpt() {
var $inp = $('#newOptIpt');
var v = $inp.val();
$('#modSelect').append('<option value="' + v + '">' + v + '</option>');
$inp.val('')
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<select id="modSelect">
<option value="default-1">Default option</option>
</select>
<br><br>
<input id="newOptIpt"/>
<button onclick="newOpt();">Add Option</button>

Manually type in a value in a "Select" / Drop-down HTML list?

In a Windows Forms application, a drop-down selector list also gives the user the option of typing an alternate value into that same field (assuming the developer has left this option enabled on the control.)
How does one accomplish this in HTML? It appears as if it is only possible to select values from the list.
If it's not possible to do this with straight HTML, is there a way to do this with Javascript?
It can be done now with HTML5
See this post here HTML select form with option to enter custom value
<input type="text" list="cars" />
<datalist id="cars">
<option>Volvo</option>
<option>Saab</option>
<option>Mercedes</option>
<option>Audi</option>
</datalist>
I faced the same basic problem: trying to combine the functionality of a textbox and a select box which are fundamentally different things in the html spec.
The good news is that selectize.js does exactly this:
Selectize is the hybrid of a textbox and box. It's jQuery-based and it's useful for tagging, contact lists, country selectors, and so on.
The easiest way to do this is to use jQuery : jQuery UI combobox/autocomplete
ExtJS has a ComboBox control that can do this (and a whole host of other cool stuff!!)
EDIT: Browse all controls etc, here: http://www.sencha.com/products/js/
Another common solution is adding "Other.." option to the drop down and when selected show text box that is otherwise hidden. Then when submitting the form, assign hidden field value with either the drop down or textbox value and in the server side code check the hidden value.
Example: http://jsfiddle.net/c258Q/
HTML code:
Please select: <form onsubmit="FormSubmit(this);">
<input type="hidden" name="fruit" />
<select name="fruit_ddl" onchange="DropDownChanged(this);">
<option value="apple">Apple</option>
<option value="orange">Apricot </option>
<option value="melon">Peach</option>
<option value="">Other..</option>
</select> <input type="text" name="fruit_txt" style="display: none;" />
<button type="submit">Submit</button>
</form>
JavaScript:
function DropDownChanged(oDDL) {
var oTextbox = oDDL.form.elements["fruit_txt"];
if (oTextbox) {
oTextbox.style.display = (oDDL.value == "") ? "" : "none";
if (oDDL.value == "")
oTextbox.focus();
}
}
function FormSubmit(oForm) {
var oHidden = oForm.elements["fruit"];
var oDDL = oForm.elements["fruit_ddl"];
var oTextbox = oForm.elements["fruit_txt"];
if (oHidden && oDDL && oTextbox)
oHidden.value = (oDDL.value == "") ? oTextbox.value : oDDL.value;
}
And in the server side, read the value of "fruit" from the Request.
I love the Shadow Wizard answer, which accually answers the question pretty nicelly.
My jQuery twist on this which i use is here. http://jsfiddle.net/UJAe4/
After typing new value, the form is ready to send, just need to handle new values on the back end.
jQuery is:
(function ($)
{
$.fn.otherize = function (option_text, texts_placeholder_text) {
oSel = $(this);
option_id = oSel.attr('id') + '_other';
textbox_id = option_id + "_tb";
this.append("<option value='' id='" + option_id + "' class='otherize' >" + option_text + "</option>");
this.after("<input type='text' id='" + textbox_id + "' style='display: none; border-bottom: 1px solid black' placeholder='" + texts_placeholder_text + "'/>");
this.change(
function () {
oTbox = oSel.parent().children('#' + textbox_id);
oSel.children(':selected').hasClass('otherize') ? oTbox.show() : oTbox.hide();
});
$("#" + textbox_id).change(
function () {
$("#" + option_id).val($("#" + textbox_id).val());
});
};
}(jQuery));
So you apply this to the below html:
<form>
<select id="otherize_me">
<option value=1>option 1</option>
<option value=2>option 2</option>
<option value=3>option 3</option>
</select>
</form>
Just like this:
$(function () {
$("#otherize_me").otherize("other..", "put new option vallue here");
});
Telerik also has a combo box control. Essentially, it's a textbox with images that when you click on them reveal a panel with a list of predefined options.
http://demos.telerik.com/aspnet-ajax/combobox/examples/overview/defaultcs.aspx
But this is AJAX, so it may have a larger footprint than you want on your website (since you say it's "HTML").

Categories