Capturing form input in JQuery - javascript

Right now I have my form set up with a generic button. Would it be easier to use a submit?
I'm trying to capture the user input and then pass it on as part of a URL. Using .find has been getting me an array of something else.
div class="username-input form-horizontal">
<!-- <div class="form-group"> -->
<label for="inputUsername" class="col-sm-3 control-label">Username</label>
<div class="col-sm-5">
<input type="text" value="Username" id="inputUsername">
</div>
</div>
<button class="signup-button col-sm-1 control-label"> Sign in </button>
<script>
$(document).ready(function() {
$(".signup-button").click(function() {
var usernameInput = $('form').find('input[type=text]')
console.log(usernameInput)
});
});

You're accessing the element not the value. Use val for it
var usernameInput = $('form').find('input[type=text]').val(); // now you get input

Since you have input field ID & it should be unique so you can use ID as selector also.
var name = $("#inputUsername").val();

You have to access value. This is the way you can access value of input text.
$(document).ready(function() {
$(".signup-button").click(function() {
var usernameInput = $('#inputUsername').val();
console.log(usernameInput);
});
});

Related

How to access form data nested inside divs (TypeScript)

In a following code I want to access user data written in a form each time user presses an enter key after typing some text data inside an input field in chat-form. Do you have any idea how can I access the following text-data using TypeScript? I have already tried with jQuery but none of the tested code seems to work. I am new to web-dev but very eager to learn new things.
<div id="chat-container">
<div id="search-container">
<input type="text" placeholder="search" />
</div>
<div id="conversation-list">
</div>
<div id="new-message-container">
+
</div>
<div id="chat-title">
</div>
<div id="chat-message-title">
</div>
<div id="chat-form">
<input id="chat-form" type="text" placeholder="Type a message!" />
</div>
</div>
first, you should use a semantic HTML by using form tag instead of div so u can use enter key to handle the submit action. second, it is not an appropriate way to duplicate an id for two different elements because id is a unique identifier for the element. finally here is a simple form and it might be helpful.
HTML:
<form id="my-form">
<input type="text" id="my-input" />
<button type="submit" id="submit-btn">send</button>
</form>
JS:
const formEl = document.getElementById("my-form") as HTMLFormElement;
const inputEl = formEl.querySelector("my-input") as HTMLInputElement;
const submitBtnEl = formEl.querySelector("submit-btn") as HTMLButtonElement;
formEl.addEventListener("submit", e => {
e.preventDefault();
// do what you want
});
inputEl.addEventListener("change", (e:Event|any) => {
console.log(e.target.value)
// do what you want
})
Before the answer: you have duplicated id="chat-form"
<div id="chat-form">
<input id="chat-form"type="text" placeholder="Type a message!"/>
</div>
Example
// select element
const elInput: HTMLInputElement = document.querySelector(`#chat-form-input`)
// add onkeypress listener
document.onkeypress = function (e: any) {
// use e.keyCode
if (e.key === 'Enter') {
// code for enter
console.log(elInput)
console.log(elInput.value)
}
}
<body>
<div id="chat-container">
<div id="search-container">
<input type="text" placeholder="search"/>
</div>
<div id="conversation-list">
</div>
<div id="new-message-container">
+
</div>
<div id="chat-title">
</div>
<div id="chat-message-title">
</div>
<div id="chat-form-container">
<input id="chat-form-input" type="text" placeholder="Type a message!"/>
</div>
</div>
</body>
You should try using a combination of JQuery.
Using this, you should put an id on the input element like so:
<input type="text" id="inputField" placeholder="search"/>
Then query the input field with JQuery. Best practice would suggest to store it in a local variable as well.
let inputFieldText = $("#inputField");
Then test for the value in the text field object as returned from JQuery.
if(inputFieldText.val()){
console.log(inputFieldText.val())
}
For reference, there is also a way to do so with document.getElementById("inputField"). Just link this function to a button that runs on pressing it (such as a "submit" button). Hope this helps!

set the value from an input field on my html page in Localstorage

How can I set the value from an input field on my html page with localstorage.
Like if I type something in an input field for example "Hello" and I press on a button Submit. Then the title from the page should change to "Hello". But it needs to be saved in localstorage if possible.
<p>Hello</p>
<div class="form-group">
<label for="text">Change title:</label>
<input type="text" class="form-control inputBox" id="text" name="text">
</div>
<button>submit</button>
You can save value to localStorage with localStorage.setItem and localStorage.getItem to get localStorage value. Here is the working example.
$(document).ready(function(){
if(localStorage.getItem("inputvalue")){
$('p').text(localStorage.getItem("inputvalue"));
}
$('button').on('click', function() {
localStorage.setItem("inputvalue", $('#text').val());
$('p').text(localStorage.getItem("inputvalue"));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Hello</p>
<div class="form-group">
<label for="text">Change title:</label>
<input type="text" class="form-control inputBox" id="text" name="text">
</div>
<button>submit</button>
You will need some Javascript for this.
You can take the value of the input like so :
var inputValue = document.getElementById("text").value;
Then you can set that into the localStorage.
localStorage.setItem("text", inputValue );
Then you can retrieve the value from local storage with
var valueFromStorage = localStorage.getItem("text")
Identify your submit button and your text area for your header :
<button id="submit">submit</button>
<p id="heading-title">
Then get the click event for that button and perform your DOM update.
var submitButton = document.getElementById("submit");
submitButton.addEventListener("click", function(e) {
document.getElementById("heading-title").innerHTML = valueFromStorage;
})
References
GetElementById
LocalStorage

jQuery input validation not working after on newly created input field with jquery append function

i'm using jQuery append function to clone the input fields on front-end, it is working fine but the issue is i have validation on parent element, it is not working on the newly append input fields. This is my jQuery code.
jQuery(function($) {
$("#addChild").click(function() {
$(".name-field:first").clone().find("input").val("").end()
.removeAttr("id")
.appendTo("#additionalselects")
.append($('<a class="delete" href="#"><i class="fa fa-times"></i></a>'));
});
$("body").on('click', ".delete", function() {
$(this).closest(".name-field").remove();
});
});
//Validation
$(document).ready(function() {
$('.name-field').on('input', function() {
// added for bit of simplicity or you can directly get valuess
var name = $('input[name="firstname"]').val();
var date = $('input[name="date"]').val();
if (name != "" && date != "") {
// values seems filled remove class
$('#stepname').removeClass('disabled');
} else {
// user has emptied some input so add class again.
$('#stepname').addClass('disabled');
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="name-field" class="name-field row">
<div class="col-xs-12 col-sm-6 childname">
<div class="field text-left">
<label class="text-left">Name of child</label>
<input id="firstname" class="firstname" name="firstname" type="text" />
</div>
</div>
<div class="col-xs-12 col-sm-6 dateofbirth">
<div class="field text-left">
<label class="text-left">Date of birth</label>
<input type="text" class="date" id="thedate" name="date" />
</div>
</div>
</div>
Next Step
Can anyone help me with this, how can achieve this?
Thanks in advance.
As you are adding .name-field dynamically so event are not binding to the new rows try to change your parent element like,
$('#additionalselects').on('input','.name-field input',function(){
//^^^ use other static element or document if not works
var parent = $(this).closest('.name-field'); // get the parent of focused input
var name = parent.find('input[name="firstname"]').val();
var date = parent.find('input[name="date"]').val();
$('#stepname').toggleClass('disabled',(!name || !date));
});
Also you should make the below changes in your HTML,
Remove all id which are part of cloning
Make an array of fields which are to be cloned like firstname[]

Disable or Enable buttons based on some conditions

In my app I have multiple divs which look like (The divs are created dynamically):
<div class="form-group clearfix">
<div class="form-group first-name">
<input type="text" id="firstName0" class="signup-input firstName required" name="first[0]" placeholder="">
</div>
<div class="form-group last-name">
<input type="text" id="lastName0" class="signup-input lastName" name="last[0]" placeholder="optional">
</div>
<div class="form-group email">
<input type="text" data-index="0" id="inputMail0" class="signup-input mail" name="email[0]" placeholder="e.g. example#url.com" aria-invalid="true">
<span class="common-sprite sign-up-cross first"></span>
</div>
</div>
The names are dynamically generated according to the index (For example the are email[1], email[2].....).
I have a button which should be disabled in case the field of the first name is not empty and the field of the email is empty and the span hasn't a class of disNone.
How should I disable the button according to above condition?
If I understand you correctly, you want to disable the button if all of the following conditions are met:-
First name field is NOT empty - $('#firstName0').val() != ''
Email field IS empty - $('#inputMail0').val() == ''
Span does NOT have class of disNone - !$('span').hasClass('disNone')
So I would check that condition this way by wrapping it in a listener on the keyup event upon the form:
$('.form-group').on('keyup', function () {
console.log('keyup');
if ($('#firstName0').val() !== '' && $('#inputMail0').val() === '' && !$('.email span').hasClass('disNone')) {
//Now do whatever with your button.
$('.mybutton').prop('disabled', true);
} else {
$('.mybutton').prop('disabled', false);
}
});
Demo: http://jsfiddle.net/ajj87Lg3/
Hope this condition works out for you.
Store the jQuery objects in variables and use that variables instead, which is a much better way to do it.
$(function(){
var firstName = $('#firstName0').val();
var inputMail = $('#inputMail0').val();
var checkClass = $('span').hasClass('disNone');
if( firstName!=='' && inputMail==='' && !checkClass ) {
$('button').attr('disabled','disabled'); //in the fiddle you would see an alert, you just have to replace that code with this one
}
});
EDIT: If your DIVS are being generated dynamically you can use the each() jquery function to loop through them.
$(function(){
$('#mainDiv').children('div').each(function(index,element){
var nameDiv = $(element).find(":nth-child(1)");
var firstName = $(nameDiv).find('input').val();
var emailDiv = $(element).find(":nth-child(3)");
var inputMail = $(emailDiv).find('input').val();
var spanElem = $(emailDiv).find("span");
var checkClass = $(spanElem).hasClass('disNone');
if(firstName!=='' && inputMail==='' && !checkClass){
$('button').attr('disabled','disabled');
//in the fiddle you would see a console.log('hi'), you just have to replace that code with this one for whatever button you want to disable
}
});
});
Checkout the FIDDLE LINK
In the fiddle I have left out one SPAN tag with class disNone and other SPAN tag without class disNone. So only once the condition executes

Reusing the same function in javascript for elements using the same classes not working

Javascript:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#first").keyup(function(event){
event.preventDefault();
ajax_check("#first");
});
$("#last").keyup(function(event){
event.preventDefault();
ajax_check("#last");
});
});
function ajax_check(current)
{
var check=$(current).val();
$.post("validate.php", {tocheck : check}, function(filled) {
if(filled == '1')
{
$(".check").html("");
$(".ajax_check").removeClass("error");
$(".ajax_check").addClass("success");
}
else
{
$(".check").html("");
$(".ajax_check").removeClass("error");
$(".ajax_check").removeClass("success");
}
})
}
HTML
<div class="control-group ajax_check">
<label class="control-label" for="first">First Name</label>
<div class="controls">
<input type="text" id="first" class="validate" placeholder="First" required>
<span class="help-inline check" ></span>
</div>
</div>
<div class="control-group ajax_check">
<label class="control-label" for="last">Last Name</label>
<div class="controls">
<input type="text" id="last" class="validate" placeholder="Last" required>
<span class="help-inline check" ></span>
</div>
</div>
The issue I'm having is when I enter in info for one of the input, the other one gets highlighted too, which isn't suppose to happen. And I think my code is kind of sloppy, but I'm trying to reuse the ajax_check function instead of making a function for each input field.
Is there a way I could reuse the function for both of the inputs? I'm new to Javascript, so I'm kind of lost. Thank you!
http://i.imgur.com/BiLObRF.png
it has to do with the scope you're requesting .check within in the ajax call. You're going back to document-level (instead of just within the current node). A simple change makes this work as intended:
var $this = $(current), // store reference to jquery object
$scope = $this.closest('.ajax_check'), // set scope to .ajax_check
check = $this.val();
$.post("validate.php", {tocheck : check}, function(filled) {
if(filled == '1')
{
// use .find() to search _within_ $scope and not across
// the entire document.
$scope.find(".check").html("");
$scope.removeClass("error").addClass("success");
}
else
{
// same thing, search within $scope
$scope.find(".check").html("");
$scope.removeClass("error success");
}
})
You can also refactor your bindings a bit to make this a little more brief as well:
$("#first,#last").keyup(function(event){
event.preventDefault();
ajax_check(this); // this is automatically going to be #first or #last
// just by the selector above
});
You can use comma to add items in selector, you can use this to get current element,
$("#first, #last").keyup(function(event){
event.preventDefault();
ajax_check('#'+this.id);
});
OR, pass object instead of id.
$("#first, #last").keyup(function(event){
event.preventDefault();
ajax_check($(this));
});
function ajax_check(current)
{
var check=current.val();
You need to save the this reference and search the closest form :
function ajax_check(e)
{
e.preventDefault()
var $this = $(this)
var check=$this.val();
$.post("validate.php", {tocheck : check}, function(filled) {
$this.siblings(".check").html("");
$this.closest(".ajax_check").removeClass("error").toggleClass("success", filled == '1');
})
}
$("#first, #last").keyup(ajax_check);
siblings
closest

Categories

Resources