How to get value from custom dropdown list? - javascript

guys. I made a custom dropdown list, but can't get its value right.
So basically I need to save the value of a chosen dropdown element and use it in the form along with other data.
Any ideas how to fix this?
<form method="post" action="/subscribed.php">
<ul>
<li>
<input type="name" placeholder="Name" name="name" id="name" />
</li>
<li>
<input type="email" placeholder="Your email" name="email" id="email" />
</li>
<li>
<input type="hidden" name="data-value" id="data-value">
<div class="wrapper-demo">
<div id="dd" class="wrapper-dropdown-3" tabindex="1">
<span>Option</span>
<ul class="dropdown">
<li>option1</li>
<li>option2</li>
<li>option3</li>
<li>option4</li>
<li>option5</li>
</ul>
</div>
</div>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script type="text/javascript">
function DropDown(el) {
this.dd = el;
this.placeholder = this.dd.children('span');
this.opts = this.dd.find('ul.dropdown > li');
this.val = '';
this.index = -1;
this.initEvents();
}
DropDown.prototype = {
initEvents : function() {
var obj = this;
obj.dd.on('click', function(event){
$(this).toggleClass('active');
return false;
});
obj.opts.on('click',function(e){
var opt = $(this);
var el = e.target;
obj.val = opt.text();
obj.index = opt.index();
obj.placeholder.text(el.getAttribute("data-value"));
$('data-value').val(el.getAttribute("data-value"));
});
},
getValue : function() {
return this.val;
},
getIndex : function() {
return this.index;
}
}
$(function() {
var dd = new DropDown( $('#dd') );
$(document).click(function() {
// all dropdowns
$('.wrapper-dropdown-3').removeClass('active');
});
});
</script>
</li>
<li>
<input type="submit" value="Submit" />
</li>
</ul>
</form>

you are using $('data-value') that is wrong selector, use $('#data-value'),
if you are selecting using id then put # before that. $('#elementid');
Demo

Related

Edit button jquery function

How do I make my to do list able edit input through the edit button using jquery? It is a to do list and i want users to be able to edit the input
Thanks in advance
<header data-role="header">
<h1>To Do List</h1>
Home
</header>
<div role="main" class="todo- container">
<div class="input">
<input type="text" class="note" placeholder="Input new note..">
<button id="addButton">Add</button>
</div>
<ul class="todo-list">
<li>
<div class="button-center">
</div>
</li>
</ul>
<script>
$(document).ready(function() {
$('#addButton').click(function() {
var task = $(".note").val();
$(".todo-list").append(`<li> <span>Task: ${task}</span><div class="button-center"><button class="deleteButton">Delete</button><button class="editButtton">Edit</button> </div></li>`);
$(".note").val("");
});
$(document).on('click', '.deleteButton', function() {
$(this).parent().parent().remove();
});
});
$('#editButton').click(function() {});
</script>
I have done something like this : example
user will be able to edit by double click at the text and an input field will showed up. user can click the edit button once he/she finished edit and the text will be updated.
JS
$('#addButton').click(function() {
var task = $(".note").val();
$(".todo-list").append(`<li>Task: <span class='task'>${task}</span><div
class="button-center"><button class="deleteButton">Delete</button><button
class="editButton">Edit</button> </div></li>`);
$(".note").val("");
});
$(document).on('click', '.deleteButton', function() {
$(this).parent().parent().remove();
});
$(document).on('dblclick', '.task', function() {
var task = $(this).text();
$(this).text('');
$(this).append(`<input type="text" value="${task}" />`);
});
$(document).on('click', '.editButton', function() {
var task = $(this).parents().siblings('span').children('input').val();
$(this).parents().siblings('span').remove('input');
$(this).parents().siblings('span').text(task);
});
I've modify your code and added the edit functionality. It's supposed to work as you will expect so I will not say much. Kindly try this
$(document).ready(function() {
var $note = $('.note');
var $taskId = $('.task-id');
$('#addButton').click(function() {
var task = $note.val().trim();
var id = $taskId.val();
if( task.trim() === '' ){
// do nothing
}else if( id !== '' ){ // edit
$(".todo-list").find('[data-id="'+id+'"] .task').text(task);
}else{ // add todo
id = new Date().getTime(); // you can make it more unique
$(".todo-list").append(`
<li data-id="${id}">
<span class="task">${task}</span>
<div class="button-center">
<button class="deleteButton">Delete</button>
<button class="editButton">Edit</button>
</div>
</li>
`);
}
$note.val('').focus();
$taskId.val('');
$(this).text('Add');
});
// delete and edit action
$(document).on('click', '.deleteButton', function() {
$(this).closest('li').remove();
}).on('click', '.editButton', function(){
let $li = $(this).closest('li');
$note.val( $li.find('.task').text() );
$taskId.val( $li.data('id') );
$('#addButton').text('Update');
});
// cancel update if .note text is cleared
$('.note').on('input', function(){
if( $(this).val() === '' ){
$taskId.val('').focus();
$('#addButton').text('Add');
}
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="input">
<input type="text" class="note" placeholder="Input new note..">
<input type="hidden" class="task-id">
<button id="addButton">Add</button>
</div>
<ul class="todo-list"></ul>

Add bullet to multiple textarea and hidden textareas

I'm trying to add bullets to multiple textarea. This works fine when the textareas are not hidden, however I'd like to be able to add bullets to newly created textareas (click on the button "Add New". Ideally I'd like also newly created bullets to go to the next line rather than to be displayed side by side.
$(document).ready()
$('.add-bullet').click(function() {
$(this).parent().next('textarea').val(function(idx, value){
return value + '\u2022';
});
return false;
});
(function($) {
"use strict";
var itemTemplate = $('.workExperience-template').detach(),
editArea = $('.workExperience-area'),
itemNumber = 1;
$(document).on('click', '.workExperience-area .add', function(event) {
var item = itemTemplate.clone();
item.find('[name]').attr('name', function() {
return $(this).attr('name') + '_' + itemNumber;
});
++itemNumber;
item.prependTo(editArea);
});
$(document).on('click', '.workExperience-area .rem', function(event) {
editArea.children('.workExperience-template').last().remove();
});
$(document).on('click', '.workExperience-area .del', function(event) {
var target = $(event.target),
row = target.closest('.workExperience-template');
row.remove();
});
}(jQuery));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="textarea">
<div>Add bullet</div>
<textarea id="todolist" class="todolist" name="todolist" placeholder="Write something.." ></textarea>
</div>
<div class="hidden">
<div class="workExperience-template">
<div class="textarea">
<div>Add bullet</div>
<textarea id="list" class="list" name="tata" placeholder="Write something.." ></textarea>
</div>
</div>
</div>
<div class="workExperience-area">
<button type="button" class="add buttonBlueAddField">Add New</button>
</div>
You should attach click event on newly created anchors:
$(document).ready()
$('.add-bullet').click(function() {
$(this).parent().next('textarea').val(function(idx, value){
return value + '\u2022';
});
return false;
});
(function($) {
"use strict";
var itemTemplate = $('.workExperience-template').detach(),
editArea = $('.workExperience-area'),
itemNumber = 1;
$(document).on('click', '.workExperience-area .add', function(event) {
var item = itemTemplate.clone();
item.find('[name]').attr('name', function() {
return $(this).attr('name') + '_' + itemNumber;
});
++itemNumber;
item.find(".add-bullet").click(function() {
$(this).parent().next('textarea').val(function(idx, value){
return value + '\u2022\n';
});
return false;
});
$(".textarea").next().append(item);
});
$(document).on('click', '.workExperience-area .rem', function(event) {
editArea.children('.workExperience-template').last().remove();
});
$(document).on('click', '.workExperience-area .del', function(event) {
var target = $(event.target),
row = target.closest('.workExperience-template');
row.remove();
});
}(jQuery));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="textarea">
<div>Add bullet</div>
<textarea id="todolist" class="todolist" name="todolist" placeholder="Write something.." ></textarea>
</div>
<div class="hidden">
<div class="workExperience-template">
<div class="textarea">
<div>Add bullet</div>
<textarea id="list" class="list" name="tata" placeholder="Write something.." ></textarea>
</div>
</div>
</div>
<div class="workExperience-area">
<button type="button" class="add buttonBlueAddField">Add New</button>
</div>

Adding elements to an ordered list on click using jquery

Entering the data in the input field and on clicking the 'Add New' button, element should be added in the list. Here, help me to find out the error
$(document).ready(function() {
var dataAdd = [];
$("#addNew").click(function() {
dataAdd.push($(this).data('#nameList'));
console.log(data.length);
});
});
<ol id="nameList">
<li>aston</li>
<li>baily</li>
<li>clairne</li>
</ol>
<input type="text" id="data" placeholder="Enter data">
<button id="addNew">Add New</button>
Seems like you need smth like:
$(document).ready(function () {
$("#addNew").click(function(){
$("#nameList").append("<li>" + $("#data").val() + "</li>");
});
});
This works:
var dataAdd = [];
$("#addNew").click(function() {
$('#nameList').append('<li>'+$('#data').val()+'</li>');
});
I don't understand what are you doing here...
dataAdd.push($(this).data('#nameList'));
You can access DOM elements with jQuery just referencing css-selector in brackets, like this $('css-selector')
That snippet does the trick:
$(document).ready(function() {
var dataAdd = [];
$("#addNew").click(function() {
var value = $('#data').val();
if(value) {
dataAdd.push(value);
$('#nameList').append('<li>' + value + '</li>');
$('#data').val('');
}
console.log(dataAdd.length);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ol id="nameList">
<li>aston</li>
<li>baily</li>
<li>clairne</li>
</ol>
<input type="text" id="data" placeholder="Enter data">
<button id="addNew">Add New</button>
You have to append the li with the value of input type text not the button.
$(document).ready(function() {
var dataAdd = [];
$("#addNew").click(function() {
dataAdd.push($('#data').val());
$('#nameList').append('<li>'+$('#data').val()+'</li>');
console.log(dataAdd.length);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ol id="nameList">
<li>aston</li>
<li>baily</li>
<li>clairne</li>
</ol>
<input type="text" id="data" placeholder="Enter data">
<button id="addNew">Add New</button>
$(document).ready(function() {
var dataAdd = [];
$("#addNew").click(function() {
var htm='<li>'+$('#data').val()+'</li>';
$("#nameList").append(htm);
$('#data').val('');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<ol id="nameList">
<li>aston</li>
<li>baily</li>
<li>clairne</li>
</ol>
<input type="text" id="data" placeholder="Enter data">
<button id="addNew">Add New</button>

Basic Calculator - event binding using pure javascript

I am completely new to the Javascript .When I am looking to get the value to the button its get failed.I already given the setEvent.Like getEle();
And also bind the click function, Now i want to get the input values and perform mathematical calculations.
<!DOCTYPE html>
<html>
<head>
<title>Simple Calculator</title>
<link rel="stylesheet" type="text/css" href="calculator.css">
</head>
<body>
<div id="container" >
<div class="calculator">
<ul>
<li>
<div id="display">
<span id="math"></span>
<span id="number"></span>
</div>
</li>
<li>
<button class="input" value="7">7</button>
<button class="input" value="8">8</button>
<button class="input" value="9">9</button>
<button class="control" value="/">÷</button>
<button class="undo" value="-1">←</button>
</li>
<li>
<button class="input" value="4">4</button>
<button class="input" value="5">5</button>
<button class="input" value="6">6</button>
<button class="control" value="*">×</button>
<button class="clear">C</button>
</li>
<li>
<button class="input" value="1">1</button>
<button class="input" value="2">2</button>
<button class="input" value="3">3</button>
<button class="control" value="-">-</button>
<button class="control" value="%">%</button>
</li>
<li>
<button class="input size2" value="0">0</button>
<button class="input" value=".">∙</button>
<button class="control" value="+">+</button>
<button class="submit">=</button>
</li>
</ul>
</div>
</div>
</body>
<script type="text/javascript" src="calculator.js"></script>
</html>
javascript
function setEvent(evt, ele, callback) {
var ele = getEle(ele);
if (ele.length === undefined) {
ele.addEventListener(evt, callback, false);
} else if(ele.length > 0) {
for (var i=0; i<ele.length; i++) {
ele[i].addEventListener(evt, callback, false);
}
}
return false;
}
function getEle(ele) {
var _idf = ele.charAt(0);
if (_idf == "#") {
var _ele = document.getElementById(ele.substr(1));
return _ele;
} else if(_idf == ".") {
var _els = document.getElementsByClassName(ele.substr(1));
return _els;
}
return ele;
}
setEvent("click", ".input", function() {
console.log(this.value);
});
setEvent("click", ".control", function() {
console.log(this.value);
});
function setEvent(evt, ele, callback) {
var ele = getEle(ele);
if (ele.length === undefined) {
ele.addEventListener(evt, callback, false);
} else if(ele.length > 0) {
for (var i=0; i<ele.length; i++) {
ele[i].addEventListener(evt, callback, false);
}
}
return false;
}
function getEle(ele) {
var _idf = ele.charAt(0);
if (_idf == "#") {
var _ele = document.getElementById(ele.substr(1));
return _ele;
} else if(_idf == ".") {
var _els = document.getElementsByClassName(ele.substr(1));
return _els;
}
return ele;
}
function getInnerHtml(id) {
return document.getElementById(id).innerHTML;
}
function getValue(elem) {
return elem.value;
}
setEvent("click", ".input", function() {
console.log(this.value);
var _num = getInnerHtml("number");
_num = _num + "" + getValue(this);
document.getElementById("number").innerHTML = _num;
});
setEvent("click", ".control", function() {
console.log(this.value);
var _num1 = document.getElementById("number").innerHTML;
_num1 = _num1 + "" + this.value;
document.getElementById("number").innerHTML = _num1;
});
setEvent("click", ".clear", function() {
console.log(this.value);
var _num1 = document.getElementById("number").innerHTML;
_num1 = "";
document.getElementById("number").innerHTML = _num1;
});
setEvent("click", ".submit", function() {
console.log(this.value);
var _num1 = document.getElementById("number").innerHTML;
_num1 = eval( _num1 + "" + getValue(this));
document.getElementById("number").innerHTML = _num1;
});
Hope this will work out.
You can print the values to the screen by using document.getElementById("number").innerHTML = this.value.
Notie that it is not jquery, when calling getElementById you don't do("#id") only ("id"), JavaScript will match the string with the desired Id.
In jquery, it is much like the behavior of css, so in order to find ID you don't do getElementById instead, you just do
//$ means jquery
$("#id")
which is equivalent to java script's getElementById.

Knockout.js unable to update server database

The following is my single page app using Knockout.js and MVC WebApi. I have no problem getting the data from WebApi service. However, I can't neither do a PUT nor a POST to the server. When I click the Update button which is bound to self.update(), it always says "baseApiUri/api/user/undefined". I thought the self.user(new userViewModel(user)) line would set the scope of the current user record, but it doesn't seem to be the case. I'd like to use the userViewModel instead of hard code the getting and setting of each of the properties in the user observable object. Thank you for your help.
#model App4MVC4.Controllers.UserViewModel
#section scripts{
<script type="text/javascript">
function viewModel() {
var baseApiUri = "#Model.apiBaseUrl";
var self = this;
/********** nested view model **********/
function userViewModel(user) {
var self = this;
self.user_ID = user.user_ID;
self.firstName = user.firstName;
self.lastName = user.lastName;
self.long_name = ko.computed(function(){return self.firstName + " " + self.lastName});
self.Login = user.Login;
self.dateAdded = user.dateAdded;
self.email = user.email;
self.alertOptIn = user.alertOptIn ? "Yes" : "No";
self.active = user.active ? "Yes" : "No";
}
/********** properties **********/
self.newUser = ko.observable();
self.userBeforeEdit = ko.observable();
self.users = ko.observableArray();
self.user = ko.observable();
self.operationStatus = ko.observable();
/********** methods **********/
// create new user (HttpPost)
self.create = function (formElement) {
self.operationStatus("Creating ...");
$(formElement).validate();
if ($(formElement).valid()) {
$.post(baseApiUri + "/api/user", $(formElement).serialize(), null, "json")
.done(function (o) {
self.users.push(o);
})
.fail(function (xhr, textStatus, err) {
self.operationStatus(err);
});
}
}
self.cancelAdd = function () {
self.newUser(new userViewModel());
}
}
// instantiate the above ViewModel and apply Knockout binding
ko.applyBindings(new viewModel());
// make jQuery tabs
$("#tabs").tabs();
</script>
}
<div id="tabs">
<ul>
<li>User Detail</li>
<li>New User</li>
</ul>
<div id="addNewTab">
<form>
<div>
<label for="firstNameNew">First Name</label>
<input type="text" title="First Name" data-bind="value:newUser.firstName"/>
</div>
<div>
<label for="lastNameNew">Last Name</label>
<input type="text" title="Last Name" data-bind="value: newUser.lastName"/>
</div>
<div>
<label for="fullNameNew">Full Name</label>
<input type="text" title="Full Name" data-bind="value: newUser.long_Name"/>
</div>
<div>
<label for="loginNew">Login</label>
<input type="text" title="Login" data-bind="value: newUser.Login"/>
</div>
<div>
<label for="emailNew">Email</label>
<input type="text" title="Email" data-bind="value: newUser.email"/>
</div>
<div>
<label for="emailAlertNew">Email Alert</label>
<span><input data-bind="checked: newUser.alertOptIn" type="radio" title="Send Email Alert" value="Yes" name="alertOptIn"/>Yes</span>
<span><input data-bind="checked: newUser.alertOptIn" type="radio" title="No Email Alert" value="No" name="alertOptIn"/>No</span>
</div>
<div>
<input type="button" value="Save" data-bind="click: create" />
<input type="button" value="Cancel" data-bind="click: cancelAdd" />
<p data-bind="text: operationStatus" class="status"></p>
</div>
</form>
</div>
</div>
you missed parentheses when retrieving a value for user here:
url: baseApiUri + "/api/user/" + self.user().user_ID

Categories