Set selected default value of dropdown dynamically - javascript

How to change default selected value in DropDownList using Javascript?
I am new to JavaScript and i'm stuck at changing default selected value in dropdown list.
Here i want to change my default selected value "111" to the new value. It has to change after i enter the text e.g."abc" into the Modal and when i hit the "Ok" button.Now it has to display default selected("abc")in to the dropdown list which i get from the text box of the modal. And also the old values has not changed in the list.
Code Snippet :
<form>
<select id="myList">
<option>111</option>
<option>222</option>
<option>333</option>
</select> <br>
<br>
</form>
<!-- Trigger/Open The Modal -->
<button id="myBtn">Open Modal</button>
<!-- The Modal -->
<div id="myModal" class="modal">
<!-- Modal content -->
<div class="modal-content">
<span class="close">×</span>
<input type="text" id="addtext" size="50" /><br>
Write & add text in the Dropdown list..</text>
<br><br>
<button id="okBtn">OK</button>
</div>
</div>
<script>
// Get the modal
var modal = document.getElementById('myModal');
// Get the button that opens the modal
var btn = document.getElementById("myBtn");
// Get the button that add text in the dropdown
var btn1 = document.getElementById("okBtn");
// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close")[0];
// When the user clicks the button, open the modal
btn.onclick = function() {
modal.style.display = "block";
}
btn1.onclick = function(){
//var element = document.getElementById('addtext');
var y = document.getElementById("addtext");
var x = document.getElementById("myList");
var option = document.createElement("option");
option.text = y.value;
x.add(option, option.defaultSelected, x[0] );
modal.style.display = "none";
}
// When the user clicks on <span> (x), close the modal
span.onclick = function() {
modal.style.display = "none";
}
// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
}
}
</script>
I think i had done something wrong at
option.text = y.value;
x.add(option, option.defaultSelected, x[0] );

You can use HTMLSelectElement.selectedIndex property to set the index of the selected option.
If you set it to 0, it will select the first option.
You can add an option to a select using HTMLSelectElement.add(). The correct syntax is (from the docs):
collection.add(item[, before]);
item is an HTMLOptionElement or HTMLOptGroupElement
before is optional
and an element of the collection, or an index of type long,
representing the item item should be inserted before. If this
parameter is null (or the index does not exist), the new element is
appended to the end of the collection.
You were using three arguments, instead of two.
So, one possible approach is:
btn1.onclick = function(){
/* ... */
x.add(option, 0 ); //add as the first item, always
x.selectedIndex = 0; //select the first item
/* ... */
}
Working demo: https://jsfiddle.net/mrlew/w1zqL0h9/
As said, if you pass null as a second argument, it will append your option to the end. And you can select it passing length-1 to the selectedIndex.
btn1.onclick = function(){
/* ... */
x.add(option, null); //add option to the end
x.selectedIndex = x.length-1; //select the last element
/* ... */
}

Related

On click slider next and previous button i get $curr[action] is not a function

I am following this Js fiddle
http://jsfiddle.net/ryt3nu1v/10/
My Result:
I am making a slider that display age as I have an array that following ages
15,25,35,45,55
I am trying to display them in slider
expected behavior is to see the next age when i click on next button
Code that I used from fiddle according to my need is
//Age slider
$('div.result-age:gt(0)').hide(); //Hide all but the first one
var $allSlides = $('div.result-age'),
traverseDefault = "first", //set the defaults
actionDefault ="arrow-next";
$('.arrow-next,.selected-arrow-left-pointer').click(function(){
var traverse = traverseDefault,
action = actionDefault;
if($(this).is('.selected-arrow-left-pointer')){ //if action is prev
traverse = "last"; //set traverse to last in case nothing is available
action = "selected-arrow-left-pointer"; //set action to prev
}
var $curr = $allSlides.filter(':visible'), //get the visible slide
$nxtTarget = $curr[action](".result-age"); //get the next target based on the action.
$curr.stop(true, true).fadeIn(1000).hide(); //hide current one
if (!$nxtTarget.length){ //if no next
$nxtTarget = $allSlides[traverse](); //based on traverse pick the next one
}
$nxtTarget.stop(true, true).fadeIn(1000); //show the target
});
//age slider end
And this is my HTML
<div class="result-box">
<div class="selected-arrow-left-pointer"></div>
<div class="result-age"><span><h4 v-for="(row,key,index) in ages">ALL ages here currently being display all at once</h4></span></div>
<div class="arrow-next"></div>
</div>
My current style is that age will be displayed in center with left and right sides having next and previous button
What am I missing?
Your v-for is creating mutliple h4 tag but you need create result div for each numbers so move your v-for inside your div tag .Then , you are using wrong values for actionDefault and action it should be next & prev where next refer to next slide and prev refer to previous slide not the classnames .
Demo Code :
$('div.result-age:gt(0)').hide();
var $allSlides = $('div.result-age'),
traverseDefault = "first",
actionDefault = "next"; //use next ..refer next node
$('.arrow-next,.selected-arrow-left-pointer').click(function() {
var traverse = traverseDefault,
action = actionDefault;
if ($(this).is('.selected-arrow-left-pointer')) {
traverse = "last";
action = "prev"; //use prev..refer prev..
}
var $curr = $allSlides.filter(':visible');
$nxtTarget = $curr[action](".result-age");
$curr.stop(true, true).fadeIn(1000).hide();
if (!$nxtTarget.length) {
$nxtTarget = $allSlides[traverse]();
}
$nxtTarget.stop(true, true).fadeIn(1000);
});
span.next,
span.prev {
cursor: pointer;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<div class="result-box">
<div class="selected-arrow-left-pointer">
<< </div>
<!--your div should have ` v-for="(row,key,index) in ages"`-->
<div class="result-age"><span><h4>1</h4></span></div>
<div class="result-age"><span><h4>2</h4></span></div>
<div class="result-age"><span><h4>3</h4></span></div>
<div class="arrow-next"> >> </div>
</div>
I found the issue, you were using arrow-next instead of next, and selected-arrow-left-pointer instead of prev. Check the below working snippet. The data can be provided dynamically as you wish, currently I have given static data.
The next and prev are reserved keywords and hence the $curr[action] was expecting a function in return, while in your case it was `$curr['arrow-next'] instead of $curr['next'], which was returning undefined, and hence the error occurred.
//Age slider
$("div.result-age:gt(0)").hide(); //Hide all but the first one
var $allSlides = $("div.result-age"),
traverseDefault = "first", //set the defaults
actionDefault = "next";
$(".next,.prev").click(function () {
var traverse = traverseDefault,
action = actionDefault;
if ($(this).is(".prev")) {
//if action is prev
traverse = "last"; //set traverse to last in case nothing is available
action = "prev"; //set action to prev
}
var currentData = $allSlides.filter(":visible"), //get the visible slide
$nxtTarget = currentData[action](".result-age"); //get the next target based on the action.
currentData.stop(true, true).fadeIn(1000).hide(); //hide current one
if (!$nxtTarget.length) {
//if no next
$nxtTarget = $allSlides[traverse](); //based on traverse pick the next one
}
$nxtTarget.stop(true, true).fadeIn(1000); //show the target
});
.next, .prev {
cursor: pointer;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="result-box">
<div class="prev"><</div>
<div class="result-age">
<span><h4>ALL ages here currently being display all at once</h4></span>
</div>
<div class="result-age">
<span><h4>2</h4></span>
</div>
<div class="result-age">
<span><h4>3</h4></span>
</div>
<div class="result-age">
<span><h4>4</h4></span>
</div>
<div class="result-age">
<span><h4>5</h4></span>
</div>
<div class="next">></div>
</div>

How can I insert an input element dynamically into a modal?

I am working on a modal for user inputs. The available inputs depend on the button/case the user clicked, e.g. in one case the modal should offer a text input, and in another case, the modal should show a radio button.
Therefore, I want to insert the input element of my modal dynamically with JavaScript.
Tested in a simple html page my code works, but not within the modal.
Is there anything special about modals I missed? How can I adjust my code to get the input element?
<html lang="en">
<div id="workModal" class="w3-modal">
<div class="w3-modal-content">
<span class="close">×</span>
<h4>Input</h4>
<div id="mod_in"></div>
</div>
</div>
</html>
<script>
var modal = document.getElementById("workModal");
var span = document.getElementsByClassName("close")[0];
span.onclick = function() {modal.style.display = "none";};
window.onclick = function(event) {if (event.target == modal {modal.style.display = "none";}}
// here starts the filling of the modal:
function build_modal(info) {
let element = document.getElementById("mod_in");
let inElement = "";
info.dataInputs.forEach(function (item){
inElement = document.createElement("input");
if (item.dataType.includes('string')){
inElement.setAttribute("type", "text");
}
if (item.minOccurs > 0) {inElement.required = true}
element.appendChild(inElement)
});
element.innerHTML = inElement;
let modal = document.getElementById("workModal");
modal.style.display = "block";
}
</script>
Instead of the input element, I get a [object HTMLInputElement] in my html code.
you have to use like below code for append new elements in html :
$("button").click(function(){ //you can call your function after any events
$("p").append("<b>Appended text</b>"); //you can append every element instead of <b>
});

Saving only the first word of a paragraph in a javascript variable

I am trying to store a paragraph in a javascript variable. I have multiple buttons inside a table, each one of the buttons has a different value, the value of each button is a small text paragraph. When i click a button a save the current buttons value in a javascript variable called 'input'.
When a button is clicked i also load an html form called "contactForm" and i display the buttons value inside that form.
The functionality works fine, the problem though is that when i save the value of the button in the ('input') js variable it saves only the first word of the paragraph, is there a way to fix this?
<html>
<div id="contactForm" >
<p><h4><i>First Choose the clients and then the file which will be uploaded in order to proced</i></h4></2>
<hr>
<input type="text" id="someInput" name="someInput"></input>
<hr>
</div>
<script>
var input; //prepare var to save contact name/ PLACE outside document ready
$(function() {
// contact form animations
$('button[id="contactbutton"]').click(function() {
input = $(this).val(); //set var input to value of the pressed button
document.getElementById("someInput").value = input;
$('#contactForm').fadeToggle();
})
$(document).mouseup(function (e) {
var container = $("#contactForm");
if (!container.is(e.target) // if the target of the click isn't the container...
&& container.has(e.target).length === 0) // ... nor a descendant of the container
{
container.fadeOut();
}
});
});
</script>
<html>
It's simple and it works... I just didn't include the additional jQuery that you've written, as for getting the first word from a paragraph, it does do that though.
<div id="contactForm" >
<p>First Choose the clients and then the file which will be uploaded in order to proced</p>
<hr>
<input type="text" id="someInput" name="someInput">
<hr>
</div>
<br>...
<br>
<h4>Demo</h4>
<button id ="contactbutton">Click Me</button>
<script>
/**
* #description the purpose of this function is to demonstrate how to
* get the first word of a paragraph, sentence, etc.
*/
!function() {
var btn = document.querySelector('button[id="contactbutton"]');
btn.addEventListener("click", function(){
// get the paragraph tag text
var para = document.querySelector("#contactForm p").textContent;
console.log(para);
// break the paragraph into an arraywor each word seperated by a space
// index 0 = first element in the array
var word = para.split(" ")[0];
console.log(word);
// another example
var inp = document.querySelector("input#someInput");
var inpVal = inp.value;
console.log(inpVal);
var word2 = inpVal.split(" ")[0];
console.log(word2);
});
}();
</script>

HTML list, Adding JQuery to cross selected item.

I have a little app that adds items to a list. The items appear with a button next to them, I want to be able to press that button to add a (text-decoration: line-through). I have tried a few different things but nothing seems to work (the Javascript to add items, delete the last item, add classes to the new li elements, etc. All that works fine, my problem is only with the JQuery part, more comments on the code itself).
HTML
<html>
<body>
<h1> Shopping List </h1>
<button id="add"> Add </button>
<input type="text" id="input" placeholder="Enter Items"> </input>
<button id="remove"> Remove Last </button>
<ul id="list">
</ul>
</body>
</html>
Js/Jq:
document.getElementById("add").addEventListener('click', function() {
var check = document.createElement("button");
var input = document.getElementById("input").value;
var newEl = document.createElement("li");
var newText = document.createTextNode(input);
var buttonText = document.createTextNode("Check");
newEl.className = "liEl";
newEl.appendChild(newText);
newEl.appendChild(check);
check.setAttribute("class", "checked");
check.appendChild(buttonText);
/* Problem starts here */
$("button.checked").on('click', function() {
$('li.liEl').css('text-decoration: line-through');
/* It should get the button with the class "checked" and on click, make the li elements with class "liEl" to have that css... */
}
);
var position = document.getElementsByTagName("ul")[0];
position.appendChild(newEl);
document.getElementById("input").value = "";
document.getElementById('input').onkeypress = function(e) {
if (e.keyCode == 13) {
document.getElementById('add').click(); /* adds an event listener to the submit text, keyCode 13 equals the enter key so when it's pressed it presses the add button. */
}
}
});
/* Delete last item function: */
document.getElementById("remove").addEventListener('click', function() {
var els = document.getElementsByTagName("li");
var removeEl = els[els.length - 1]; // <-- fetching last el, If els is an array, it has indices from 0 to els.length - 1. 0 is the first, els.length - 1 is the last index.
var containerEl = removeEl.parentNode;
containerEl.removeChild(removeEl);
});
Use style like $('li.liEl').css('text-decoration','line-through');
Your jQuery css function is wrong, you need to provide two parameter to set css value (see this: css-property-name-value).
Your selector syntax ($('li.liEl')) is not right, it would return all <li> element, not the one the clicked button is located.
You can use this: $(this).parent().css('text-decoration', 'line-through');.
Your code contain some bug, the last added button would not trigger the function. It is because your click function is added before the new element added to DOM. And it would cause your click function to be triggered multiple time for earlier added button.
Here's the snippet for fixed code. Since you already using jQuery, I change several native java script native element query and event handler whith jquery syntax.
$(function () {
$("#add").click(function(evt) {
var input = $('#input').val();
var check = $('<button class="checked">Check</button>');
var newEl = $('<li class="liEl"></li>');
newEl.append(input);
newEl.append(check);
$(check).click(function(evt) {
$(this).parent().css('text-decoration', 'line-through');
});
$('#list').append(newEl);
$('#input').val('');
});
$('#remove').click(function(evt) {
var lastEl = $('li.liEl').last();
lastEl.remove();
});
$('#input').keypress(function(evt) {
if (evt.keyCode === 13) {
$("#add").click();
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<body>
<h1> Shopping List </h1>
<button id="add"> Add </button>
<input type="text" id="input" placeholder="Enter Items" />
<button id="remove"> Remove Last </button>
<ul id="list"></ul>
</body>

How to show/hide content

I have a page where I would like two buttons which when one is clicked, displays hello, and when the other one is clicked would hide the "hello" message and then display "goodbye". I know this needs to be done in javascript but I am not good with javascript.
Check this snippet
<p id="msg"></p>
<button onclick="helloFunction()">Say Hello</button>
<button onclick="byeFunction()">Wave Goodbye</button>
<script>
function helloFunction() {
document.getElementById("msg").innerHTML = "Hello";
}
function byeFunction() {
document.getElementById("msg").innerHTML = "Goodbye";
}
</script>
There are a couple of ways to do it, one of which would be affecting the visiblity of dom elements which say hello or goodbye, the other method as illustrated below you would actually change the text of a dom object based on which button is pressed
<button onClick="javascript:say('Hello');">Say Hi</button>
<button onClick="javascript:say('Goodbye');">Say Goodbye</button>
<div id="TextField"></div>
<script>
function say(text) {
var element = document.getElementById("TextField");
element.innerHTML = text;
}
</script>
here what you'll need to achieve such a feat.
first create a div or a p tag to hold ur text and two buttons
eg
<div id="container">Hello</div>
<button id="show">Show</button>
<button id="hide">Show</button>
make sure your div has an id and you buttons too. You use that for reference.
then in your javascript, you can either toggle the display or visibility of the div
<script type="text/javascript">
//Declare variable
var div = document.getElementById("container");
var show = document.getElementById("show");
var hide = document.getElementById("hide");
//run when windows fully loads
window.onload = function(){
//when i click show button
show.onclick = function(){
div.style.display = "block";
}
//when i click hide button
hide.onclick = function(){
div.style.display = "none";
}
}
//That is champ, this is all vanilla javascript. You can also look into implementing with jquery.
</script>

Categories

Resources