Selected options in bootstrap selectpicker displays as undefined in angular JS controller - javascript

On clicking the search button, the selected item must get displayed in the console. But it displays "hey undefined".
This is my html code
<div ng-controller="filterController">
<select name="model" id="model" multiple title="Any" data-live-search="true" style="display:none;" class="selectpicker" ng-model="select">
<option value="1" ng-selected="true">Restaurant</option>
<option value="2">Vegetarian</option>
<option value="3">Bar</option>
<option value="4">Night Life</option>
<option value="5">Breakfast</option>
<option value="6">Fast Food</option>
<option value="7">Steak & Grill</option>
</select>
<button class="btn btn-default" style="margin-top: 25px;" ng-click="search()"></button>
</div>
This is my jquery code.
$(document).ready(function($) {
var select = $('select');
if (select.length > 0 ){
select.selectpicker();
}
var bootstrapSelect = $('.bootstrap-select');
var dropDownMenu = $('.dropdown-menu');
bootstrapSelect.on('shown.bs.dropdown', function () {
dropDownMenu.removeClass('animation-fade-out');
dropDownMenu.addClass('animation-fade-in');
});
bootstrapSelect.on('hide.bs.dropdown', function () {
dropDownMenu.removeClass('animation-fade-in');
dropDownMenu.addClass('animation-fade-out');
});
bootstrapSelect.on('hidden.bs.dropdown', function () {
var _this = $(this);
$(_this).addClass('open');
setTimeout(function() {
$(_this).removeClass('open');
}, 100);
});
This is my controller function.
angular.module('myApp',[]).controller('filterController', function($scope) {
$scope.search = function(){
console.log('hey',$scope.select);
}
Could someone please tell me what to do?

In this, you use multiple so you get selected value in an array so if you want to console any selected value then you have to console like $scope.select[0].

Related

Get the selected option inside a <select> tag with javascript

Hello I am trying to get the value from a select tag, using javascript, that is generated within a razor view using C#.
This is the html where the select tag is generated:
<form id="asignRol" method="post">
<select name="users" id="userChange">
#foreach (var user in Model.UserAndRolesInfo)
{
<option value="#user.Username">#user.Username</option>
}
</select>
<select name="rol" id="roleChange">
#foreach (var rol in #Model.roleAvailability)
{
<option value="#rol.Name">#rol.Name</option>
}
</select>
<button type="button" id="submitButton" class="btn btn-primary">Asignar rol</button>
</form>
The html select tag is generated as expected:
HTML phot
In a different js file I am trying to get the values of the selected options:
var submitButton = document.getElementById("submitButton");
var userSelect = document.getElementById("userChange");
var userSelectValue = userSelect.options[userSelect.selectedIndex].value;
var roleSelect = document.getElementById("roleChange");
var roleSelectValue = roleSelect.value;
submitButton.addEventListener("click", function () {
console.log(userSelectValue);
console.log(roleSelectValue);
})
With the result of only getting the default value:
Result
I tried passing the event and event.preventdefault.
You need to get the value when the event occurs not before it. In your case event click.
var submitButton = document.getElementById("submitButton");
var userSelect = document.getElementById("userChange");
var roleSelect = document.getElementById("roleChange");
submitButton.addEventListener("click", function() {
var userSelectValue = userSelect.options[userSelect.selectedIndex].value;
var roleSelectValue = roleSelect.options[roleSelect.selectedIndex].value;
console.log(userSelectValue);
console.log(roleSelectValue);
})
<form id="asignRol" method="post">
<select name="users" id="userChange">
<option value="#user.Username">#user.Username</option>
<option value="moses">moses</option>
<option value="cat">cat</option>
<option value="dog">dog</option>
</select>
<select name="rol" id="roleChange">
<option value="#rol.Name">#rol.Name</option>
<option value="mouse">mouse</option>
<option value="elephant">elephant</option>
<option value="fox">fox</option>
</select>
<button type="button" id="submitButton" class="btn btn-primary">Asignar rol</button>
</form>

Drop-down clicked, a form created

enter image description here
This error message keeps opening on console.
And I am using Ember.js
I am trying to make a drop-down and whenever on option from a drop-down is clicked, a form should be made based on what an option is chosen. For example, there are 3 options on dropdown: name, text, drop-down. When a user click a text, a text form should be created below. I already made an dropdown and tried to implement by writing document.write(" < /h1>"), but it keeps saying uncaught syntax error. Can someone help me please?
<script type="text/javascript">
function clicking(option) {
if (option === "name")
//document.write("<h1>Hello<h1>");
}
</script>
<h1>Data Form Test</h1>
<div id="dropdown">
<form>
<select id="selectBox" onchange="clicking(this)">
<option value="" disabled="disabled" selected="selected" style="display:none">Please select a option</option>
<option value="name">Name</option>
<option value="title">Title</option>
<option value="text">Text</option>
<option value="check-box">Check-box</option>
<option value="drop-down">Drop-down</option>
<option value="calendar">Calendar</option>
</select>
</form>
</div>
<div id="div1"></div>
<script type="text/javascript">
function clicking(option) {
if (option == "name"){
//document.write("<h1>Hello<h1>");
}
}
</script>
and on html
onchange="clicking(this.value)"
You can't access your selected value via option, you need to use property value instead. In my example I changed option with event.
To write some HTML/text into div/selector use .innerHTML method instead of document.write.
See working example.
function clicking(event) {
if (event.value === "name")
document.getElementById('div1').innerHTML = "<h1>Hello<h1>";
}
<h1>Data Form Test</h1>
<div id="dropdown">
<form>
<select id="selectBox" onchange="clicking(this)">
<option value="" disabled="disabled" selected="selected" style="display:none">Please select a option</option>
<option value="name">Name</option>
<option value="title">Title</option>
<option value="text">Text</option>
<option value="check-box">Check-box</option>
<option value="drop-down">Drop-down</option>
<option value="calendar">Calendar</option>
</select>
</form>
</div>
<div id="div1"></div>
If you would like to use your form to perform for example an ajax request. Here is another example I created for you.
I used addEventListener to show to different approach of handling your clicking function.
Read my comments.
// Our selectors
var form = document.getElementById('example-form');
var select = document.getElementById('selectBox');
var result = document.getElementById('result');
// Let's add an event listener to our form, we will listen whenever we submit the form
form.addEventListener('submit', function(e) {
var elements = this.querySelectorAll('input, select');
var formData = {};
for(i = 0; i < elements.length; i++) {
var element = elements[i];
Object.assign(formData, { [element.name] : element.value })
}
console.log(formData);
// Now you can perform some ajax call eg.
// I've commented it out, but code works, you just need to replace url
//$.ajax({
// url: 'http://example.com/action/url/',
// type: 'post',
// data: formData, // our form data
// success: function(response) {
// result.innerHTML = response;
// }
//})
// Prevent Page from autoreloading
e.preventDefault();
return false;
});
// Another approach of handling your clicking function is by passing eventListener to select
select.addEventListener('change', function(e) {
// Log
//console.log(e.target.value);
// We can use switch here for example
// Code becomes more readable
switch (e.target.value) {
case 'name':
case 'title':
case 'text':
result.innerHTML = '<h1>Hello ' + e.target.value + '</h1>';
default:
break;
}
});
<form id="example-form">
<select id="selectBox" name="selectBox">
<option value="" disabled="disabled" selected="selected" style="display:none">Please select a option</option>
<option value="name">Name</option>
<option value="title">Title</option>
<option value="text">Text</option>
<option value="check-box">Check-box</option>
<option value="drop-down">Drop-down</option>
<option value="calendar">Calendar</option>
</select>
<input name="example1" value="" placeholder="example input 1" />
<input name="example2" value="" placeholder="example input 2" />
<button type="submit">Submit me</button>
</form>
<div id="result"></div>

jQuery setting & getting localstorage data for dropdowns & input's

I'm trying to make a simple form page have some localstorage functionality to restore settings/input after the page has been closed/reloaded.
I've attempted to make a start but I am still learning so there are mistakes and I can't get it to work.
If a change is made to the name input field it should update the localstorage with the new name.
If a change is made to any of the dropdown (selector? option?) fields it should update the localstorage with the new value.
On page load it should automatically restore all of the values.
The "Clear" button should ONLY reset the dropdown (selector? option?) fields to blank, it should NOT reset the name field.
Example: https://jsfiddle.net/5gam3b6f/
$(document).ready(function () {
$.each($("select"), function (index, value)) {
localStorage.getItem($(this).attr(“id”));
};
});
$("select").on("change", function () {
localStorage.setItem($(this).attr(“id”), $(this));
});
I haven't managed to start on the name input field or the clear function yet because I can't even get the first one to work.
I would rather not use external libraries as this is as complicated as it will get, nothing else needed.
The below will work for you:
Here is a working jsFiddle
jQuery
$('.useLocalSelect').change(function () {
var key = $(this).attr('id');
var value = $(this).val();
localStorage.setItem(key, value)
});
// use a timer for text fields and the like so that localsotrage is set 2 seconds after the user stops typing instead of after each keystroke
var t = '';
$('.useLocalInput').keyup(function () {
clearTimeout(t);
var key = $(this).attr('id');
var value = $(this).val();
t = setTimeout(function () {
localStorage.setItem(key, value)
}, 2000);
});
$('.useLocal').each(function () {
var key = $(this).attr('id');
if (localStorage.getItem(key)) {
$(this).val(localStorage.getItem(key));
}
});
$('.clearLocalSelect').click(function () {
$('.useLocalSelect').each(function () {
$(this).val('');
var key = $(this).attr('id');
localStorage.removeItem(key);
});
});
html
<label style="color: #01ACEE; font: bold 14px Tahoma;">Input
<input class="useLocal useLocalInput" id="testInput" size="40" type="text" name="website" value="" required/>
</label>
<br/>
<br/>
<label style="color: #01ACEE; font: bold 14px Tahoma;">Select</label>
<select class="useLocal useLocalSelect" id="testSelect" name="start_date">
<option value="">Select one...</option>
<option value="January">January</option>
<option value="February">February</option>
<option value="March">March</option>
<option value="April">April</option>
<option value="May">May</option>
<option value="June">June</option>
<option value="July">July</option>
<option value="August">August</option>
<option value="September">September</option>
<option value="October">October</option>
<option value="November">Noember</option>
<option value="December">December</option>
</select>
<br/>
<br/>
<input type="button" class="clearLocalSelect" value="Clear Selects"/>

Creating a text and dropdown list search functionality

I've written a piece of code that allows a Sharepoint list user to select a search criteria from a drop down list. By default, next to this, I'd like a textbox to be present. Besides the text box on the page is a Search button and a Reset button. This looks like this:
Ideally, what I'd like is that if the user selects a specific option in the search criteria drop down list (say, Field 3), the text box will change to a drop down list, which they choose their option from and then search for as usual.
This is what I have so far:
<script type="text/javascript">
function RedirectUrl() {
var sField = document.getElementById("searchField").value;
if (sField == "Field3") {
var search = document.getElementById("dropdownSearch").value;
} else {
var search = document.getElementById("textSearch").value;
}
var url = "";
if (search != "") {
url = "FilterName=" + sField + "&FilterMultiValue=*" + search + "*";
window.location.href = //Url of our site
}
else {
return false;
}
}
function ClearUrl() {
//Refresh page
}
</script>
Search Field: <select id="searchField">
<option selected value="Field1" >Field 1</option>
<option value="Field2">Field 2</option>
<option value="Field3">Field 3</option>
<option value="Field4">Field 4</option>
</select>
if (searchField == "Field3") {
Search text: <select id="dropdownSearch" />
<option selected value="One" >One</option>
<option value="Two">Two</option>
</select>
} else {
Search text: <input type="text" id="textSearch" />
}
</script>
<input type="button" id="btnSearch" value="Search" onclick="return RedirectUrl();" />
<input type="button" id="btnClear" value="Reset Filters" onclick="return ClearUrl();" />
The functionality of this code works. If the user selects "Field3" from the search field drop down list, whatever is selected in the drop down list is shown. If the user selects any other option from the search field drop down list, the text in the "search text" field is shown.
However, due to the if statement contained within, it looks like this:
Questions:
How can I get the code to automatically display either the text box or the drop down list depending on the user's selection in the Search Field?
How can I hide the if statement logic?
As can probably be guessed from the code I have almost zero experience in Javascript (and absolutely zero experience in JQuery, if any answers tend that way) - although I have tagged JQuery as from what little I do know I feel it might be better(?) suited for it.
Edit: My not-working code after ZiNNED's help:
Search Field:
<select id="searchField">
<option selected value="Field1">Field 1</option>
<option value="Field2">Field 2</option>
<option value="Field3">Field 3</option>
<option value="Field4">Field 4</option>
</select>Search Text:
<select id="dropdownSearch" style="display: none;">
<option value="1">Value 1</option>
<option value="2">Value 2</option>
<option value="3">Value 3</option>
</select>
<input id="textSearch" />
<input type="button" id="btnSearch" value="Search" />
<script type="text/javascript" src="link-to-Sharepoint/SiteAssets/jquery-1.11.1.js">
$(document).ready(function () {
$(document).on("change", "#searchField", function () {
var show = $(this).val() == "Field3";
$("#dropdownSearch").toggle(show);
$("#textSearch").toggle(!show);
});
});
</script>
You should do a couple of things.
First: remove the if-statement from the code and hide the dropdownSearch select by default:
HTML
Search Field: <select id="searchField">
<option selected value="Field1" >Field 1</option>
<option value="Field2">Field 2</option>
<option value="Field3">Field 3</option>
<option value="Field4">Field 4</option>
</select>
Search text:
<select id="dropdownSearch" style="display: none;" />
// All options and their values
</select>"
<input type="text" id="textSearch" />
Second, add a reference to jQuery and the following JavaScript to your document:
$(document).ready(function () {
$(document).on("change", "#searchField", function () {
var show = $(this).val() == "Field3";
$("#dropdownSearch").toggle(show);
$("#textSearch").toggle(!show);
});
});
This adds an event to the searchField dropdown that triggers when its value is changed. If the value equals Field3 the dropdownSearch is shown; otherwise the textSearch.
See this FIDDLE.
EDIT: After your edit, try changing the following:
<script type="text/javascript" src="link-to-Sharepoint/SiteAssets/jquery-1.11.1.js">
$(document).ready(function () {
$(document).on("change", "#searchField", function () {
var show = $(this).val() == "Field3";
$("#dropdownSearch").toggle(show);
$("#textSearch").toggle(!show);
});
});
</script>
to:
<script type="text/javascript" src="link-to-Sharepoint/SiteAssets/jquery-1.11.1.js"></script>
<script>
$(document).ready(function () {
$(document).on("change", "#searchField", function () {
var show = $(this).val() == "Field3";
$("#dropdownSearch").toggle(show);
$("#textSearch").toggle(!show);
});
});
</script>
You shouldn't add JavaScript to script tags when you're also referring to an external file in it.

how to display selected value from dropdownlist to label using javascript

I have 3 drop-down lists in my form. I want to display the selected value from each dropdown list to my label. The problem is that only one dropbox list will display, while the other two won't.
Here is my code:
<script>
window.onload = function()
{
document.getElementsByName('mydropdown')[0].onchange = function(e)
{
document.getElementById('mylabel').innerHTML = this.value;
};
}
</script>
this is my html
<td><select name="mydropdown" id="mydrop" onchange="">
<option value="none" selected="selected"></option>
<option value="17.50">6M</option>
<option value="25.00">12M</option>
</select>
</td>
<td><label id="mylabel"></label></td>
<td><select name="mydropdown" id="mydrop">
<option value="none" selected="selected">Length </option>
<option value="0.0455">DS516HO</option>
<option value="0.0559">DS520HO</option>
<option value="0.0780">DS516HWR</option>
<option value="0.0200">DS312WH</option>
<option value="0.0624">DS520WH</option>
<option value="0.0361">DS525FH</option>
<option value="0.1170">DS620HW</option>
<option value="0.1340">DS550HW</option>
<option value="0.1340">TD525HW</option>
<option value="0.1820">DS650HW</option>
<option value="0.2340">TD665HWR</option>
</select>
<td><label id="mylabel"></label></td>
You're only binding the zeroth element (the one you selet) with [0]. You need to bind to all of them, possibly like so:
Array.prototype.forEach.call(document.getElementsByName('mydropdown'),
function (elem) {
elem.addEventListener('change', function() {
document.getElementById('mylabel').innerHTML = this.value;
});
});
http://jsfiddle.net/UNLnx/
By the way you are reusing the same ID on multiple elements which is invalid.
Update: Working example: http://jsfiddle.net/x8Rdd/1/
That's because you are only setting the onchange event for the first element in your "mydropdown" group.
<script>
window.onload = function()
{
var dd = document.getElementsByName('mydropdown');
for (var i = 0; i < dd.length; i++) {
dd[i].onchange = function(e)
{
document.getElementById('mylabel').innerHTML = this.value;
};
}
}
</script>
Or something like that. If you're using jQuery then you can set the onchange property for all of them without the loop.

Categories