searching for substring in select options without values - javascript

I am trying to search for a specific substring in text retrieved from options that are populated from mysql, how do i return the text value of the option selected so that i can search for my substring.
$(document).ready(function() {
$("borrowitem").change(function() {
$("#borrowitem option:selected").text();
var optionValue = $(this).text;
if (optionValue == "non-consumable") {
$("#showtime").hide();
} else {
$("#showtime").hide();
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="form-control input-lg borrowitem" name="borrowitem[]" required="required" id="borrowitem"><option></option></select>

why are there two two $("#showtime").hide(); & not a show() in the if else..
anyways here is code you had missed the ID selector #
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#borrowitem").change(function(){
var optionValue= $( "#borrowitem option:selected" ).val();
console.log(optionValue);
if(optionValue == "non-consumable") {
$("#showtime").hide();
}
else{
$("#showtime").show();
}
});
});
</script>
</head>
<body>
<select class="form-control input-lg borrowitem" name="borrowitem[]" required="required" id="borrowitem">
<option value="non-consumable">carrot</option>
<option value="non-consumable">potato</option>
<option value="opel">Opel</option>
<option value="non-consumable">apple</option>
</select>
<br/><hr/><br/>
<div id="showtime">SHow TIME</div>
</body>
</html>

Look for selected value as $(this).val() === 'non-consumable' inside the change event. For instance
$('#borrowitem').change(function () {
console.log($(this).val() === 'non-consumable');
});
<select id="borrowitem">
<option>non-consumable</option>
<option>consumable</option>
</select>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
If it's a multiple select, change the condition to
$(this).val().indexOf('non-consumable') !== -1

try this example code
you pass id with # in onchange event and write onchange as .on("change",function()) and get selected using $("#borrowitem option:selected").text() so it will work
$(document).ready(function() {
$("#borrowitem").on("change", function() {
// alert($("#borrowitem option:selected").text());
var optionValue = $("#borrowitem option:selected").text();
//alert(optionValue);
if (optionValue == "non-consumable") {
$("#showtime").hide();
} else {
$("#showtime").show();
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="form-control input-lg borrowitem" name="borrowitem[]" required="required" id="borrowitem"><option>test</option>
<option>non-consumable</option></select>
<span id="showtime">hello</span>

Here you go.
Something the others missed is that you have to check when the page loads what the state of the initial showtime element should be. For example: we could load it pre-hidden with non-consumable as the selected option, or we could load it shown with the selected option consumable.
One big reason we may need to do that is for a "sticky" form. Which is a form that retains it's value after a submission attempt.
To do that, all we need to do is "functionize" the action we want to take. Basically just create a function to do it, then call it from the event handler and from the onReady event when the page is ready. Instead of placing it directly in the event handler.
So Orange is consumable and then green is non-consumable. I wanted something visible so I added the orange box for the showtime. Then I wrapped that in a green box to hold the place open when it's hidden. Mainly this was to keep the select element from jumping around when the box was hidden, but I also liked the contrast.
Another thing most ( all ) of them missed is this:
so that i can search for my substring
see below for explanation
(function($){
$(document).ready(function(){
/* set state of showtime */
function setShowtimeState ()
{
var text = $('#borrowitem').find('option:selected').text();
var Regx = new RegExp(/\bnon\-consumable\b/, 'i'); //case insensitive
if( Regx.test(text) )
$('#showtime').hide();
else
$('#showtime').show();
}
//call on change of the select element
$('#borrowitem').change(setShowtimeState );
//call on ready to set the initial state
setShowtimeState ();
});
})(jQuery);
<script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>
<div id="showtime-wrapper" style="margin-bottom: 5px;width:50px;height:50px;background:green; border: 1px solid black;">
<div id="showtime" style="width:100%;height:100%;background:orange;"> </div>
</div>
<select class="form-control input-lg borrowitem" name="borrowitem[]" required="required" id="borrowitem">
<option>- pick an option - </option>
<option>non-consumable</option>
<option>consumable</option>
<option>this is non-consumable</option>
<option>this is consumable</option>
<option>Case Insensitive NON-Consumable</option>
</select>
REGx
I used a Regular Expression to match the sub-string. This is a bit complex if you never messed with them but it's the best way to match. I will walk you through the pattern I used a bit:
/\bnon\-consumable\b/
So to break this down for you
the / is called the delimiter, its used to mark the start|end of the regx
the \b matches a word boundary. For example if we use a | to mark the word boundaries for this string |foobar| |is| |a| |word|. The purpose of that is if we look for the sub-string foo, we could match that in foobar but if we look for \bfoo\b it would not match because there is no word boundary between foo and bar. This helps prevent false matches on sub-strings.
the "letters" are just letters and match literally letter for letter
then we have the closing delimter / that ends the Regx
The second argument of new RegExp is the flag, an I used the i flag for case-insensitive matching, you can omit it for case sensitive matches.
For more info https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp
One thing I feel obligated to mention is you have the name of the select borrowitem[] with the array brackets. Typically this is done for one of 2 reasons:
Pass multiple elements of this name to the server
Set the multiple flag for the select box and make it multi-select
Both of these would require some code changes. But there is a 3rd option, you just did it, because.

Related

Selecting dynamically added elements by class name

I have am HTML code which for simplicity looks like this:
<div class="main-container">
<div class="group-area group1" id="group1">
<select class="slct" id="slct1">
<option>Group A</option>
<option>Group B</option>
<option>Group C</option>
</select>
<div class="participant-area">
<!-- empty, can be filled with "<div class='participant'></div>" elements -->
</div>
</div>
<button class="add-group">Show another group</button>
</div>
In the above inteface, the user can select the name of the group from the select drop down, and the the participants of that group will be shown in the 'participant-area'. They will be drawn from a presaved list, and will be added using jQuery append:
<script>
$(document).on('change', '.slct', function() {
var number = $(this).attr("id").charAt(4); //gets the number '1' from the id name
var key = $(this).find("option:selected").val(); //gets the value to be used later
var constructedClass = ".group" + number; //result: "group1"
presavedList.forEach(participant => {
$(constructedClass + " .participant-area") //selecting participant area that is inside group1
.append($("<div>").addClass("participant")
.append($("<h2>").text(participant.name))
);
}
})
</script>
However, user can also click on the 'add-group' button at the end of the main container, and have another area just like the first one displayed, that can be used to see participants of a different group. But this time, the classes will be group2 instead of group1, slct2 instead of slct1, and so on. This is done by having a global variable that is incremented whenever the button is clicked:
<script>
var areaNumber = 1;
$(".add-group").click(function () {
areaNumber++;
$(".main-container")
.append($("<div>").addClass( "group"+areaNumber).addClass("group-area").attr("id", "group"+ areaNumber)
.append($("<select>")) //etc... Reconstruct the same one as original
.append($("<div>")) //etc... Reconstruct the same one as original
});
</script>
My problem is related selecting the groupN class of the dynamically created elements (like group2, group3, etc). In the first function above - after a second area has been created and its select value changed - the change is being detected normally and the $(document).on('change', '.slct', function() {...}) is being fired normally. However, the 5th line in that function:
$(constructedClass + " .participant-area").append(//etc)
is not working: the constructedClass is not being detected by the function, even though it exists in the time of firing it - but I believe it's not being detected because it was not present at the time of initial parsing of javascript. Is that correct? Is there any way to solve this? (Be able to select dynamically generated elements by their uniquely generated class names?).
Thank you for reading this far and for any help you can offer.
Do not use incremental id and class attributes. It is an anti-pattern. It makes your code needlessly complex, more verbose, and difficult to maintain.
A much better solution is to group common elements by behaviour using a single class attribute. That way you can use DOM traversal to relate them to each other. It also allows you to clone() content (as it's all identical) without the need to spaghetti-fy your JS by filling it with HTML.
With that said, try this:
let presavedList = [{ name: 'Foo bar' }, { name: 'Lorem ipsum' }]
$(document).on('change', '.slct', function() {
var html = presavedList.map(item => `<div class="participant"><h2>${item.name}</h2></div>`);
$(this).next('.participant-area').html(html);
});
$(".add-group").click(function() {
var $clone = $('.group:first').clone();
$clone.find('select').val('');
$clone.find('.participant-area').empty();
$clone.appendTo('.main-container');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="main-container">
<div class="group-area group">
<select class="slct">
<option value="">Please select...</option>
<option>Group A</option>
<option>Group B</option>
<option>Group C</option>
</select>
<div class="participant-area"></div>
</div>
<button class="add-group">Show another group</button>
</div>

jQuery SELECT with Textarea

Just wondering if someone can help me on a problem, I don't fully undersand why it doesn't work.
I have this fiddle, http://jsfiddle.net/uomt99zp/
What it is doing:
When you select from the drop down box, insert that word into the textarea.
Which it DOES, when the textarea isn't "touched".
If you type something into the box, and then try to select an item, it doesn't work.
I'm not sure why this doesn't update the textarea. Perhaps someone can shed some light on this issue?
<textarea name="template" required="required" class="template form-control" rows="6"></textarea>
<select class="templatesAvailableFields">
<option>Select One</option>
<option>Test1</option>
<option>Test2</option>
<option>Test3</option>
</select>
$('.templatesAvailableFields').on('change', function() {
var text = $('.templatesAvailableFields option:selected').text();
$('.template').append(text);
});
You need to set value using .val():
$('.template').val($('.template').val()+text);
Working Demo 1
Also .val() can have callback function which can be used for setting a new value:
function
Type: Function( Integer index, String value ) => String
A function returning the value to set. this is the current element. Receives the index position of the element in the set and the old value as arguments.
$('.template').val(function(i,v){ return v+ text});
Working Demo 2
You can try val(function) with old value + new text to append,
$('.templatesAvailableFields').on('change', function() {
var text = $('.templatesAvailableFields option:selected').text();
$('.template').val(function(ind,val){
return val+text;
});
});
Live Demo
To answer to the "why" it does not work, it's because, the contents of a textarea represent its default value. So, when you append an element to the textarea, you change the default value of this textarea.
So it changes the textarea as long as you did not type in. Once you typed in, the default value is no more used, even if you remove all the text of the textarea.
By using .append you are just concatinating your output string if you want only the dropdown element it would be better to use the .text() or .val() method
$('.templatesAvailableFields').on('change', function() {
var text = $('.templatesAvailableFields option:selected').text();
var existing=$('.template').val();
$('.template').val(existing+text);
});
.append(), .html() and .text() methods do not work with form elements, for setting/getting value of a from element .val() method should be used instead:
Your code is working ...i tried it in visual studio .... Only change I had made is I kept the script under the option control... I am not sure about.for me its working fine.
<body >
<textarea name="template" required="required" class="template form-control" rows="6"></textarea>
<select class="templatesAvailableFields">
<option>Select One</option>
<option>Test1</option>
<option>Test2</option>
<option>Test3</option>
</select>
<script type="text/javascript">
$('.templatesAvailableFields').on('change', function () {
var text = $('.templatesAvailableFields option:selected').text();
$('.template').append(text);
});
</script>
</body>
You should control input value's with val() method
// cache element
var $select = $('.templatesAvailableFields');
$select.change( function() {
$('.template').val($select[0].value);
});
just replace append with text
here is the updated fiddle
$('.templatesAvailableFields').on('change', function() {
var text = $('.templatesAvailableFields option:selected').text();
$('.template').text($('.template').text() + text);
// $('.template').val(text); this won't work in IE <= 7
});
http://jsfiddle.net/rrehan/uomt99zp/2/

Set option of the Select box according to JSON result

I actually have some questions but I will start with the main one. I want to set the value of Select box on the basis of JSON.
Here's the HTML in question,
<label class="lbl">Office: </label>
<select tab-index="6" class="required" name="office" class="off">
<option value="">---------</option>
<option value="U">London</option>
<option selected="selected" value="R">Delhi</option>
<option value="W">Lisbon</option>
</select>
JSON sends it like this, I can't show the full JSON since it's too big, but I will show a part, Location: "U".
Here's the JS part:
if (data.Office === "R") {
$('select option[value="Delhi"]').prop('selected', true);
}
if (data.Office === "U") {
console.log('here');
$('.off option[value="London"]').attr('selected', 'selected');
}
if (data.Office === "W") {
$('select option[value="Lisbon"]').prop('selected', true);
}
But it's not working? Can any one point out why?
Moreover, I have a list of managers say and I am also getting that in JSON. So I am doing this,
for (var i = 0; i < data.Managers.length; i++) {
find_input = $('input[name="project_manager[]"').length;
if (find_input != data.Managers.length) {
$('<input type="text" name="project_manager[]" class="" value="" />').appendTo('#managers');
}
console.log(data.Managers[i].Manager);
$('input[name="project_manager[]"').each(function() {
$(this).val(data.Managers[i].Manager);
});
}
No of textboxes depend on the number of managers, but it only sets the value of last item from the array of managers in text boxes that are appended. Why?
Moreover I am not able to set value of textarea in Firefox like this:
$('textarea#some_id').val(data.Description);
It works in Chrome though.
First you need to add the character "<" in the beginning of the 3rd option of the select box:
<option selected="selected" value="R">Delhi</option>
Now, in the JS code, your problem is that you're using the wrong value. Instead of:
$('select option[value="Lisbon"]').prop('selected', true);
You must use:
$('select option[value="W"]').prop('selected', true);
I hope it help.
I think your selectors should be of the form:
$('select option[value="R"]').prop('selected', true);
Note the value is the same as the value in the HTML, not the displayed string (i.e. 'R' instead of 'Delhi').
Also, you should be using prop() consistently for selected flag, as described here by John Resig.

Getting a Select Value after appending

This is for javascript and jquery.
I have in my body...
<select id="option1_select" name="courseCodeSelectName">
<option></option>
<option>Word1</option>
<option>Word2</option>
</select>
<script>
$("select").change(function () {
functionLoadOpt2() }).trigger("change" );
</script>
<select id="option2_select" name="courseNumSelectName">
<option></option>
</select>
<button onclick="changePage()">Load Textbook Page!</button>
As we see above, the web page has 2 select boxes and a button. Depending on what you select in the first select box loads what is in the second one, using the functionLoadOpt2 function locating higher up in my code.
if (result == "Word1") {
$("#option2_select").append('<option>Letter1</option>');
...
There is more but it follows the same code different values.
Result is the following, above the if statement(just a row up),
var result = (document.getElementById('option1_select').value);
now on the button click, the function changePage() runs,
and all I want is ...
var result = (document.getElementById('option1_select').value);
var result2= (document.getElementById('option2_select').value);
Assume they selected and option for both. Result2 doesnt work. I'd imagine because I'm appending it but how would I work around this. So that when I click changePage() I get the selected value of option1_select and option2_select.
functionLoadOpt2:
function functionLoadOpt2(){
var opt1Val = (document.getElementById('option1_select').value);
$("#option2_select").find('option').remove().end().append('<option></option>');
if (opt1Val == "Word1") {
$("#option2_select").append('<option>Letter1</option>');
$("#option2_select").append('<option>Letter2</option>');
$("#option2_select").append('<option>Letter3</option>');
$("#option2_select").append('<option>Letter4</option>');
$("#option2_select").append('<option>Letter5</option>');
}else if (opt1Val == "Word2") {
$("#option2_select").append('<option>Letter3</option>');//they have similar ones in some cases
$("#option2_select").append('<option>Letter6</option>');
$("#option2_select").append('<option>Letter7</option>');
$("#option2_select").append('<option>Letter8</option>');
$("#option2_select").append('<option>Letter9</option>');
$("#option2_select").append('<option>Letter10</option>');
$("#option2_select").append('<option>Letter11</option>');
$("#option2_select").append('<option>Letter12</option>');
$("#option2_select").append('<option>Letter13</option>');
$("#option2_select").append('<option>Letter14</option>');
$("#option2_select").append('<option>Letter15</option>');
$("#option2_select").append('<option>Letter16</option>');
$("#option2_select").append('<option>Letter17</option>');
//this works
}
}
use jQuery to get and set the value of <select> with .val()
Both your select elements have the same id, fix it the it should be fine
<select id="option1_select" name="courseCodeSelectName">
<option></option>
<option>Word1</option>
<option>Word2</option>
</select>
<select id="option2_select" name="courseNumSelectName">
<option></option>
</select>
<button onclick="changePage()">Load Textbook Page!</button>
Demo: Fiddle
Note: You can improve the script a lot by using proper jQuery constructs, like this

Dynamically Change Multiple Hidden Form Fields

I'm somewhat new to jQuery. I'm pretty sure this is possible, but I'm not quote certain how to code this.
What I'm looking to do is to use a dropdown with selections that represent ranges (e.g. if someone were searching for bedrooms, the dropdown selctions would look like "0-2", "3-5", "6+"). Then when someone chooses a selection, two hidden fields would by dynamically filled. One field with the minimum of the range, and the other field with the maximum of the range.
Here is an example of how I'm trying to structure this:
<select id="bedrooms" class="dropdown">
<option>Bedrooms</option>
<option></option>
<option value="1">0-2</option>
<option value="2">3-5</option>
<option value="3">6+</option>
</select>
<input type="hidden" name="bedrooms-from" value=''>
<input type="hidden" name="bedrooms-to" value=''>
I suppose the values of each option could change, I wasn't sure what the best way to approach that would be.
I haven't actually run this, but I think it should work:
$("#bedrooms").change(function ()
{
// Get a local reference to the JQuery-wrapped select and hidden field elements:
var sel = $(this);
var minValInput = $("input[name='bedrooms-from']");
var maxValInput = $("input[name='bedrooms-to']");
// Blank the values of the two hidden fields if appropriate:
if (sel.val() == "") {
minValInput.val("");
maxValInput.val("");
return;
}
// Get the selected option:
var opt = sel.children("[value='" + sel.val() + "']:first");
// Get the text of the selected option and split it on anything other than 0-9:
var values = opt.attr("text").split(/[^0-9]+/);
// Set the values to bedroom-from and bedroom-to:
minValInput.val(values[0]);
maxValInput.val((values[1] != "") ? values[1] : 99999999);
});
$("select").on("change", function() {
$("form").append( /* <input type='hidden'> tag here */ );
});

Categories

Resources