I have the following HTML
<li class='user_attributes'><b>username: </b>{{username}}
<input class='user_input form-control edit_fields {{_id}}' id='username_field' type="text" name='username' placeholder="username">
<button type="submit" class="btn btn-default submit_button edit_fields {{_id}}" id='update_username'>update</button>
</li>
And I'd like to get the value of the input field whenever that <li>'s submit button is clicked (not the value of other input fields with the same name).
I have the following jQuery, but all of it returns undefined:
'click #update_username': function(ev, template){
ev.preventDefault();
// var username_field = template.$('input[id="username_field"]').val();
// var username_field = $(ev.target).find('[name = message]').val();
var input_field = $(this).siblings($('input[id="username_field"]')).val();
console.log(input_field);
// Meteor.call('updateUsername', this._id, username_field);
}
EDIT
this is an issue of the framework Im using (Meteor.js) and the scope of 'this'
Try that
https://jsfiddle.net/zy7qy3v5/3/
$('button').click(function(){
var value = $(this).siblings('input').val();
alert(value);
})
Dont put an unecessary jquery object in the siblings function. Your selector is returning every siblings.
$('button').siblings('input') //Returns 1 element
is not the same as
$(this).siblings($('input[id="username_field"]')) //Returns 2 element
See https://jsfiddle.net/8x04nbyx/5/
$(document).ready(function(){
$('#update_username').on('click',function(ev, template){
ev.preventDefault();
// var username_field = template.$('input[id="username_field"]').val();
// var username_field = $(ev.target).find('[name = message]').val();
var input_field = $(this).closest('li').find('input').val();
console.log(input_field);
// Meteor.call('updateUsername', this._id, username_field);
});
});
I'm not sure if it's this that you want but give it a try:
$('#update_username').click(function(){
var test = $('#username_field').val()
alert (test)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<li class='user_attributes'><b>username: </b>{{username}}
<input class='user_input form-control edit_fields {{_id}}' id='username_field' type="text" name='username' placeholder="username">
<button type="submit" class="btn btn-default submit_button edit_fields {{_id}}" id='update_username'>update</button>
</li>
Related
I need to be able to append to a list (it's a leaderboard, but that's not relevant) by submitting through a form and appending to an ordered list using jquery. When I press submit nothing happens other than the button being pressed. Where am I going wrong?
HTML:
<main>
<ol class="playerList">
<li>Profit - 12,565</li>
<li>carpe - 11,423</li>
<li>Fate - 11,003</li>
<li>Fleta - 10,931</li>
<li>Fury - 10,704</li>
<li>Gesture - 10,601</li>
<li>Choihyobin - 10,012</li>
<li>MekO - 9,879</li>
<li>Birdring - 9,850</li>
<li>Mano - 9,766</li>
</ol>
</main>
<footer>
<form id="submissionForm">
<label id="nameLabel" for="pName"><u>Player name:</u></label>
<input id="pName" type="text" placeholder="Enter player name...">
<label for="pElims"><u>Elimination Count:</u></label>
<input id="pElims" type="text" placeholder="Enter elimination count...">
<input id="submitBtn" type="submit">
</form>
</footer>
JQuery:
$(document).ready(function() {
$("#submissionForm").on('submit', function(event){
event.preventDefault();
error = false;
$(".error").hide();
var playerName = $("#pName").var();
var elimCount = $("#pElim").var();
var newItem = (playerName + " - "+ elimCount);
$('.playerList').append('<li>'+ newItem + '</li>');
return false;
});
});
.var() is not a valid way to get an input element's value.
Also, the id on the elim count does not match the id on the HTML element.
var playerName = $("#pName").var();
var elimCount = $("#pElim").var();
It should be:
var playerName = $("#pName").val();
var elimCount = $("#pElims").val();
I have a form and when I click on the button I have to copy but it doesn't work. Even if it works I can't copy the functionality of the form.I tried to copy to generic form but it doesn't work
JQ:
$(document).ready(function() {
var addToWishList = document.querySelector('#add-to-wishlist');
var wishlistItem = document.querySelector('#wishlist-item');
var wishlist = document.querySelector('#wishlist');
var clearlist = document.querySelector('#clearlist');
var saved = localStorage.getItem('wishlistItems');
var add = document.querySelector('#eventBtn');
addToWishList.addEventListener('submit', function (event) {
event.preventDefault();
if (wishlistItem.value.length < 1) return;
wishlist.innerHTML += '<li>' + wishlistItem.value + '</li>';
localStorage.setItem('wishlistItems', wishlist.innerHTML);
}, false);
if (saved) {
wishlist.innerHTML = saved;
}
$(document).ready(function(){
$("#clearlist").click(function() {
localStorage.clear();
$("#list li").empty();
});
});
add.click(function(){
addToWishList.clone(true).appendTo("body");
});
});
And my form:
<form id="add-to-wishlist">
<button type="button" id="eventBtn">Add new list</button>
<label><h1>To do list</h1></label>
<input type="text" name="wishlist-item" id="wishlist-item">
<button type="submit">Add to Wishlist</button>
<button type="reset" id="clearlist">Delete records</button>
<ul id="list">
<li id="wishlist"></li>
</ul>
</form>
``
There are 2 issues with your approach:
1) ids have to be unique, otherwise your HTML isn't valid and won't work as expected. It's better to change to classes instead. Otherwise it would be necessary to e.g. increment a value each time you clone the form and change all ids of the cloned elements accordingly.
2) To set any event on a dynamically created element, it's necessary to delegate this event from an already existing parent element of this element that's already there when the page is initially loaded, e.g. from document.
I adjusted your code accordingly and adjusted the events to work with the specific form. The code isn't working in a stack snippet here because of the local storage, but here's a working Fiddle.
$(document).ready(function() {
var saved = localStorage.getItem('wishlistItems');
$(document).on("click", ".add", function(event) {
event.preventDefault();
let wishlistItem = $(this).closest("form").find(".wishlist-item");
let wishlist = $(this).closest("form").find(".wishlist");
if (wishlistItem.val().length < 1) return;
wishlist.append('<li>' + wishlistItem.val() + '</li>');
localStorage.setItem('wishlistItems', wishlist.html());
});
if (saved) {
$(".wishlist:eq(0)").html(saved);
}
$(document).on("click", ".clearlist", function() {
localStorage.clear();
$(this).closest("form").find(".list li").remove();
});
$(document).on("click", ".eventBtn", function() {
let newList = $(this).closest("form").clone();
newList.find(".list li").empty();
newList.find(".wishlist-item").empty();
newList.appendTo("body")
});
});
<form class="add-to-wishlist">
<button type="button" class="eventBtn">Add new list</button>
<label>
<h1>To do list</h1>
</label>
<input type="text" name="wishlist-item" class="wishlist-item">
<button class="add">Add to Wishlist</button>
<button type="reset" class="clearlist">Delete records</button>
<ul class="list">
<li class="wishlist"></li>
</ul>
</form>
How to make sure that every field has greater value than the value of previous input? If condition is true, then I can submit a form.
$('#add').on('click', function() {
$('#box').append('<div id="p1"><input required type="number" min="1" max="120" name="val" ></div>');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a id="add" href="javascript:void(0);">Add </a>
<form>
<div id="box"></div>
<input type="submit" value="Submit">
</form>
You need to loop through all the inputs, keeping the value of the previous one to compare it. Keep in mind, your current "add input" code will give all the inputs the same name, which will make it problematic to use on your action page. You can use an array for that.
$("#add").on("click", function() {
$("#box").append('<div id="p1"><input required type="number" min="1" max="120" name="val[]" ></div>');
});
$("form").submit(function(e) {
return higherThanBefore(); //send depending on validation
});
function higherThanBefore() {
var lastValue = null;
var valid = true;
$("input[name^=val]").each(function() {
var val = $(this).val();
if (lastValue !== null && lastValue >= val) { // not higher than before, not valid
valid = false;
}
lastValue = val;
});
return valid; // if we got here, it's valid
}
<a id="add" href="javascript:void(0);">Add </a>
<form action="test">
<div id="box"></div>
<input type="submit" value="Submit">
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
One line added, one line changed. Simply get the last input's value, and use that as the min value for the new input.
$('#add').on('click', function() {
// get the current last input, save its value.
// This will be used as the min value for the new el
var newMin = $("#box").find(".p1 input").last().val() || 1;
// Append the new div, but set the min value to the
// value we just saved.
$('#box').append('<div class="p1"><input required type="number" min="'+newMin+'" max="120" name="val" ></div>');
$(".p1 input").on("keyup mouseup", function(){
var triggeringEl = $(this);
if (triggeringEl.val() >= triggeringEl.attr("min") ) {
triggeringEl.removeClass("error");
}
triggeringEl.parent().nextAll(".p1").children("input").each(function(){
if($(this).attr("min") < triggeringEl.val() )
$(this).attr("min", triggeringEl.val() );
if ($(this).val() < $(this).attr("min")){
$(this).addClass("error");
} else {
$(this).removeClass("error");
}
})
})
});
.error {
border: 1px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a id="add" href="javascript:void(0);">Add </a>
<form>
<div id="box"></div>
<input type="submit" value="Submit">
</form>
So I made changes, to reflect the comments (great catch, by the way), but there is a challenge here. If I set the minimum value when the current el's value changes, works great. But I can't assume that the current el is the highest value in the collection, so if the current el is being decremented, I haven't figured the logic to decrement all subsequent minimums. Sigh...
At any rate, the section that creates the new input and sets the minimum remains the same. Then I had to add a listener to handle changes to the input. If the input is changed, by either keyboard or mouse, all subsequent minimums (minima?) are checked against this value. Those that are lower are set to this value, and then all elements are checked, minimum vs. value, and an error signal is set if needed. Still needs work, as I can't figure how to handle decrementing a value, but it's a start.
You can use .filter(): for each input field you can test if the next one has a value greater then the current one.
$('#add').on('click', function() {
var idx = $('#box').find('div[id^=p]').length;
$('#box').append('<div id="p' + idx + '"><input required type="number" min="1" max="120" name="val' + idx + '" ></div>');
});
$('form').on('submit', function(e) {
var cachedValues = $('form [type=number]');
var noOrderRespected = cachedValues.filter(function(idx, ele) {
var nvalue = cachedValues.eq(idx + 1).val();
return (+ele.value < (+nvalue||+ele.value+1)) ? false : true;
}).length;
console.log('noOrderRespected: ' + noOrderRespected);
if (noOrderRespected > 0) {
e.preventDefault();
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a id="add" href="javascript:void(0);">Add </a>
<form>
<div id="box"></div>
<input type="submit" value="Submit">
</form>
I am creating contact form on my website, but i got stuck. I don't know how to put content from variable after each inputs on my website. I can show them into console.log and works perfect but i don't know how to put it on website.
Here's the code:
(function($) {
$(document).ready(function() {
var form = $(".contact_form"),
fields = $("[data-error]");
fields.on("click", function() {
$(this).removeAttr('placeholder');
});
fields.on("blur", function() {
var field = $(this);
field.toggleClass("form_error", $.trim(field.val()) === "");
});
form.on("submit", function(e) {
var hasErrors = false;
fields.each(function(i, elem) {
var field = $(elem),
empty = $.trim(field.val()) === "",
errors = field.data("error");
console.log(errors);
// HERE IS ERROR VAR
// sth here to put it into html
field.toggleClass("form_error", empty);
if (empty) {
hasErrors = true;
}
});
if (!hasErrors) {
form.submit();
} else {
e.preventDefault();
}
});
});
})(jQuery);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="#" accept-charset="utf-8" class="contact_form">
<input type="text" placeholder="Imię" data-error="Podaj imię">
<input type="text" placeholder="Nazwisko" data-error="Podaj nazwisko">
<input type="email" placeholder="E-mail" data-error="Podaj poprawny adres e-mail">
<input type="text" placeholder="Kontakt" data-error="Podaj poprawny numer telefonu">
<textarea name="message" class="textarea_field" placeholder="WIADOMOŚĆ" data-error="Wpisz treść wiadomości"></textarea>
<button type="submit" class="przycisk">Wyślij</button>
</form>
Firstly note that presumably you're trying to check that the fields all have a value. If so, you should put the error message generation logic in the if (empty) code block.
To actually create the HTML for the messages you can use the after() method to insert the error messages after the related input element. If you also wrap the errors in an element, such as a span, which has a class you can easily use that to remove() the elements when the form is submit to be re-evaluated. Try this:
(function($) {
$(document).ready(function() {
var form = $(".contact_form"),
fields = $("[data-error]");
fields.on("click", function() {
$(this).removeAttr('placeholder');
});
fields.on("blur", function() {
var field = $(this);
var valid = $.trim(field.val()) !== "";
field.toggleClass("form_error", !valid).next('span.form_error').remove();
if (!valid)
field.after('<span class="form_error">' + $(this).data('error') + '</span>'); // add new error messages
});
form.on("submit", function(e) {
var hasErrors = false;
$('span.form_error').remove(); // Remove any old errors when submitting the form
fields.each(function(i, elem) {
var field = $(elem),
empty = $.trim(field.val()) === "",
errors = field.data("error");
if (empty) {
hasErrors = true;
field.after('<span class="form_error">' + errors + '</span>'); // add new error messages
field.toggleClass("form_error", empty);
}
});
if (!hasErrors) {
form.submit();
} else {
e.preventDefault();
}
});
});
})(jQuery);
span.form_error {
color: #C00;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="#" accept-charset="utf-8" class="contact_form">
<input type="text" placeholder="Imię" data-error="Podaj imię">
<input type="text" placeholder="Nazwisko" data-error="Podaj nazwisko">
<input type="email" placeholder="E-mail" data-error="Podaj poprawny adres e-mail">
<input type="text" placeholder="Kontakt" data-error="Podaj poprawny numer telefonu">
<textarea name="message" class="textarea_field" placeholder="WIADOMOŚĆ" data-error="Wpisz treść wiadomości"></textarea>
<button type="submit" class="przycisk">Wyślij</button>
</form>
Use text() for adding string to element or html() for adding html code.
Example:
var text = 'hello world';
$('div#textHere').text(text);
var htmlCode = "<strong>Hello</strong> World";
$('div#htmlHere').html(htmlCode);
Documentation for text() and for html().
When you want to get form field values you use $('#id').val(); the val will get value from form fields. And then you can use $('#id').html('Enter val here') that's it.
use can use text() or html()
Different:
1)If you retrieve text only, u can use text()
2)If you retrieve html element with text, then u can use html();
Eg 1 : -
var text1="hello world";
$(".text").text(text1) ==> hello world
$(".text").html(text1) ==> hello world
Eg 2 : -
var text2="<h1>hello world</h1>";
$(".text").text(text2) ==> '< h1>hello world< /h1>'
$(".text").html(text2) ==>hello world`
I have two text boxes with each having a button. On click of the button the strings have to be appended. Say I clicked the first button it will save in a string and I click on the second button the second string should be appended to the first one.
<input type="text" id="name_1"> <input type="button" id="button_1" value="add">
<input type="text" id="name_2"> <input type="button" id="button_2" value="add">
<br>
<input type="submit">
$('[id^="button_"]').on("click", function() {
name = $('#name_'+$(this).attr('id').split('_')[1]).val();
alert(name);
});
partial working demo here: jsfiddle
example: john_david where john is the first string and david is the second string
i think you are looking for this :-
$('[id^="button_"]').on("click", function() {
var name = "";
$('[id^="button_"]').each(function(){
name = name+$('#name_'+$(this).attr('id').split('_')[1]).val();
});
alert(name);
});
See DEMO
You need to use name variable as global and when click happens append string to that variable.
FIDDLE
Try this :
var name = "";
$('[id^="button_"]').on("click", function() {
if(name == ""){ name = name+$(this).prev("input").val(); }
else{ name = name+"_"+$(this).prev("input").val(); }
alert(name);
});
$('[id^="button_"]').on("click", function() {
name = $('#name_'+$(this).attr('id').split('_')[1]).val();
alert(name);
});
$('[type="submit"]').on("click", function() {
name = $('#name_1').val() + $('#name_2').val();
alert(name);
});