I am sure this question is posted before, but didn't find it in javascript/jquery.
So I have two inputs, first one is a city, and second one is a part of that specific city that we chose in first input:
$(function() {
var city = ["option1", "option2", "option3", "option4"];
$("#city").autocomplete({
source: city
});
var addressforoption1 = ["a1", "a2", "a3", "a4"];
var addressforoption2 = ["b1", "b2", "b3", "b4"];
var addressforoption3 = ["c1", "c2", "c3", "c4"];
var addressforoption4 = ["d1", "d2", "d3", "d4"];
var answer = document.querySelector('#city').value;//tried changing this to innerText or innerHTML still the same
if (answer = "option1") {
address = addressforoption1
}
if (answer = "option2") {
address = addressforoption2
}
if (answer = "option3") {
address = addressforoption3
}
if (answer = "option4") {
address = addressforoption4
}
$("#location").autocomplete({
source: address
});
});
<link rel="stylesheet" href="//code.jquery.com/ui/1.13.2/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-3.6.0.js"></script>
<script src="https://code.jquery.com/ui/1.13.2/jquery-ui.js"></script>
<label for="city">➡ City<span style="color:red;">*</span></label>
<input type="text" required name="city" id="city" placeholder="Enter your city name here">
<hr>
<label for="location">➡ Location<span style="color:red;">*</span></label>
<input type="text" required name="location" id="location" placeholder="City location">
Problem: First autocomplete works with charm, and you can pick any city you want, exactly like it should. But second autocomplete is always last one - option 4
You must use double equal sign operator (==) for comparison and then change your code to something like this
$(function() {
var city = ["option1", "option2", "option3", "option4"];
var addressforoption1 = ["a1", "a2", "a3", "a4"];
var addressforoption2 = ["b1", "b2", "b3", "b4"];
var addressforoption3 = ["c1", "c2", "c3", "c4"];
var addressforoption4 = ["d1", "d2", "d3", "d4"];
$("#city").autocomplete({
source: city,
select: function(event, ui) {
var answer = ui.item.value;
if (answer == "option1") {
address = addressforoption1
} else if (answer == "option2") {
address = addressforoption2
} else if (answer == "option3") {
address = addressforoption3
} else if (answer == "option4") {
address = addressforoption4
} else {
address = []
}
$("#location").autocomplete('option', 'source', address);
}
});
$("#location").autocomplete({
source: []
});
});
<link rel="stylesheet" href="//code.jquery.com/ui/1.13.2/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-3.6.0.js"></script>
<script src="https://code.jquery.com/ui/1.13.2/jquery-ui.js"></script>
<label for="city">➡ City<span style="color:red;">*</span></label>
<input type="text" required name="city" id="city" placeholder="Enter your city name here">
<hr>
<label for="location">➡ Location<span style="color:red;">*</span></label>
<input type="text" required name="location" id="location" placeholder="City location">
I added select and change methods to your code.
select -
You can use the select property in autocomplete to pass along the selected value, here I just call the function setAddressValue that basically does the same as what you did before.
change -
select only handles when the user actually selects the value from the autocomplete-list. if I manually enter option1 and then try, nothing is going to happen. So therefore, I added the change method which basically checks whenever a user is leaving the input field.
$(function() {
const city = ["option1", "option2", "option3", "option4"];
$("#city").autocomplete({
source: city,
select: function(event, ui) {
setAddressValue(ui.item.value);
}
}).change(function() {
setAddressValue(this.value);
});
const setAddressValue = (answer) => {
let address = [];
if (answer === "option1") address = ["a1", "a2", "a3", "a4"];
else if (answer === "option2") address = ["b1", "b2", "b3", "b4"];
else if (answer === "option3") address = ["c1", "c2", "c3", "c4"];
else if (answer === "option4") address = ["d1", "d2", "d3", "d4"];
else adress
$("#location").autocomplete({
source: address
});
}
});
<link rel="stylesheet" href="//code.jquery.com/ui/1.13.2/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-3.6.0.js"></script>
<script src="https://code.jquery.com/ui/1.13.2/jquery-ui.js"></script>
<label for="city">➡ City<span style="color:red;">*</span></label>
<input type="text" required name="city" id="city" placeholder="Enter your city name here">
<hr>
<label for="location">➡ Location<span style="color:red;">*</span></label>
<input type="text" required name="location" id="location" placeholder="City location">
Notes: if(answer = "option1") will assign option1 to answer. Essentially what you did was to check if answer was a truthy value, and a string is a truthy value. So therefore all if-cases were true., And that's why it always showed the last one, it passed through them all. You need to do == or === for comparisons.
Don't use var. Use const for variables that you wont reassign, and let for variables you want to re-assign a value to.
Related
I am trying to write a function in jQuery.
var arr1 = ["Jcob", "Pete", "Fin", "John"];
var str = $("#fname").val();
if (jQuery.inArray(str, arr1))
$("#lname").text("Bob");
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="fname" name="fname">
<input type="text" id="lname" name="lname">
Please check my fiddle here
What it will do it the user will give the value in the first input box the jQuery function will check if the value is present in that array it will fill the second input box with the given text.
Three things:
You need to add an event listener to the first input to constantly keep checking when someone inputs something.
Before selecting elements in the DOM, make sure the DOM is ready.
You don't need jQuery at all here. Like most things, very easy to do without jQuery.
const names = [ "Jcob", "Pete", "Fin", "John" ];
document.addEventListener('DOMContentLoaded', function() {
const fname = document.getElementById('fname');
const lname = document.getElementById('lname');
fname.addEventListener('input', function(event) {
lname.value = names.includes(fname.value) ? 'Bob' : '';
});
});
<input type="text" id="fname" name="fname">
<input type="text" id="lname" name="lname">
If you insist on jQuery (which I do strongly recommend you shouldn't until you are proficient with the native DOM API):
const names = [ "Jcob", "Pete", "Fin", "John" ];
$(document).ready(function() {
const $fname = $('#fname');
const $lname = $('#lname');
$fname.on('input', function(event) {
if ($.inArray($fname.val(), names) > -1) {
$lname.val('Bob');
} else {
$lname.val('');
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="fname" name="fname">
<input type="text" id="lname" name="lname">
Try this:
<body>
<input type="text" id="fname" name="fname">
<input type="text" id="lname" name="lname">
<button onclick="checkValue()">Click</button>
<script>
var arr1 = ["Jcob", "Pete", "Fin", "John"];
function checkValue() {
var str = $("#fname").val();
var val = jQuery.inArray(str, arr1);
if (val === -1) {
console.log("no value");
}
else {
$("#lname").val("Bob");
}
}
</script>
</body>
not a coder at all, making a little project. Does anyone know how I can make my input here case insensitive? I have tried to add a line similar to
name = name.map(function(x){ return x.toLowerCase() })
but this didn't work and with no coding background I'm finding it hard to troubleshoot what is going wrong.
Thank you :)
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<input id="name" type="text">
<input id="check" type="button" value="Check">
<p id="para"></p>
<script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script>
<script type="text/javascript">
$(document).ready(function() {
var names = ["B1", "B2", "B3", "B4", "B5"];
names = names.map(function(x) {
return x.toLowerCase()
})
$('#check').click(function() {
var name = $('#name').val();
if (jQuery.inArray(name, names) != '-1') {
document.getElementById("para").innerHTML = "We cover this postcode";
} else {
document.getElementById("para").innerHTML = "We do not cover this postcode ";
}
});
});
</script>
</body>
</html>
To have case insensitivity you need to have both the values in same case, whereas you're just changing value of names to lowerCase but not the value of name toLowerCase.
So just change both the values to same case and than match
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<input id="name" type="text">
<input id="check" type="button" value="Check">
<p id="para"></p>
<script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script>
<script type="text/javascript">
$(document).ready(function() {
var names = ["B1", "B2", "B3", "B4", "B5"];
names = names.map(function(x) {
return x.toLowerCase()
})
$('#check').click(function() {
var name = $('#name').val().toLowerCase(); // notice to lowercase here
if (jQuery.inArray(name, names) != '-1') {
document.getElementById("para").innerHTML = "We cover this postcode";
} else {
document.getElementById("para").innerHTML = "We do not cover this postcode ";
}
});
});
</script>
</body>
</html>
You can convert the input to lowercase using toLowerCase() and then check if is present in array or not . i.e :
$(document).ready(function() {
var names = ["B1", "B2", "B3", "B4", "B5"];
names = names.map(function(x) {
var a= x.toLowerCase()
console.log(a);
$('#check').click(function() {
var name = $('#name').val().toLowerCase();
if (jQuery.inArray(name, a) != '-1') {
document.getElementById("para").innerHTML = "We cover this postcode";
} else {
document.getElementById("para").innerHTML = "We do not cover this postcode ";
}
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<input id="name" type="text">
<input id="check" type="button" value="Check">
<p id="para"></p>
Take the text in variable, then pass it with toLowerCase() function.
var str = "Hello World!";
var res = str.toLowerCase();
var strring = "Convert String to Lower";
var result = str.toLowerCase();
I am currently getting data from a repeatable group form through serializeArray() as an object with this syntax:
group_field[0][address]:"street one"
group_field[0][number]:"10000"
group_field[0][city]:"nyc"
group_field[1][address]:"street two"
group_field[1][number]:"600"
group_field[1][city]:"washington"
group_field[2][address]:"street three"
group_field[2][number]:"34000"
group_field[2][city]:"paris"
I am trying to convert this to a multidimensional array, or nested object structure to group all the fields depending on the index between the first square brackets.
desired output:
group_fields = [
"0": {
"address": "street one",
"number": "10000",
"city": "nyc",
},
"1": {
"address": "street two",
"number": "600",
"city": "washington",
},
"2": {
"address": "street three",
"number": "34000",
"city": "paris",
},
}
I have tried several things, I will write the last point i got to after alot of different unsuccessful methods:
var values = {};
var params = {};
$.each(theForm.serializeArray(), function(i, field) {
values[field.name] = decodeURIComponent(field.value);
});
for (var key in values){
if (values.hasOwnProperty(key)) {
var matches = key.match(/[^[\]]+(?=])/g);
if(matches != null && matches.length > 0) {
var index = matches[0];
var theKey = matches[1];
var theVal = values[key];
var single = {
[theKey]: theVal,
}
params[matches[0]].push(single);
}
}
}
this obviously does not work.
Any help appreciated
What you've quoted doesn't look like the result of serializeArray, but working from what I believe your form looks like, it's not that hard. The main thing is that serializeArray returns an array of {name, value} objects, so we just have to isolate the two significant parts of the group_field names and then use those to build up our array with the objets in it. See comments:
var theForm = $("form");
// Create the array
var group_fields = [];
// Loop through the fields
theForm.serializeArray().forEach(function(entry) {
// Get the index and prop name from the entry name
var nameparts = /^group_field\[(.+)\]\[(.*)\]$/.exec(entry.name);
// Get the group entry if we already have it
var group = group_fields[nameparts[1]];
if (!group) {
// We don't, create and add it
group = group_fields[nameparts[1]] = {};
}
// Set the property (address, street, etc.)
group[nameparts[2]] = entry.value;
});
console.log(group_fields);
.as-console-wrapper {
max-height: 100% !important;
}
<form>
<input type="hidden" name="group_field[0][address]" value="street one">
<input type="hidden" name="group_field[0][number]" value="10000">
<input type="hidden" name="group_field[0][city]" value="nyc">
<input type="hidden" name="group_field[1][address]" value="street two">
<input type="hidden" name="group_field[1][number]" value="600">
<input type="hidden" name="group_field[1][city]" value="washington">
<input type="hidden" name="group_field[2][address]" value="street three">
<input type="hidden" name="group_field[2][number]" value="34000">
<input type="hidden" name="group_field[2][city]" value="paris">
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Or using ES2015+ (since you used computed property names in your original attempted solution):
const theForm = $("form");
// Create the array
const group_fields = [];
// Loop through the fields
theForm.serializeArray().forEach(entry => {
// Get the index and prop name from the entry name
const [ , index, prop] = /^group_field\[(.+)\]\[(.*)\]$/.exec(entry.name);
// Get the group entry if we already have it
var group = group_fields[index];
if (!group) {
// We don't, create and add it
group = group_fields[index] = {};
}
// Set the property (address, street, etc.)
group[prop] = entry.value;
});
console.log(group_fields);
.as-console-wrapper {
max-height: 100% !important;
}
<form>
<input type="hidden" name="group_field[0][address]" value="street one">
<input type="hidden" name="group_field[0][number]" value="10000">
<input type="hidden" name="group_field[0][city]" value="nyc">
<input type="hidden" name="group_field[1][address]" value="street two">
<input type="hidden" name="group_field[1][number]" value="600">
<input type="hidden" name="group_field[1][city]" value="washington">
<input type="hidden" name="group_field[2][address]" value="street three">
<input type="hidden" name="group_field[2][number]" value="34000">
<input type="hidden" name="group_field[2][city]" value="paris">
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
I want to search the House Name from all the input the user provided.
so if the user details are as:
[{"houseName":"man","houseType":"villa","houseFloors":"seven","houselocation":"Seattle"},{"houseName":"band","houseType":"small","houseFloors":"two","houselocation":"washington DC"}]
If i provide search as man ,it should give me as:
[{"houseName":"man","houseType":"villa","houseFloors":"seven","houselocation":"Seattle"}]
The code is as :
<html>
<head>
<title>JavaScript</title>
</head>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<label>House Name
<input type='text' name='houseName' id='houseName' placeholder="House Name">
</label>
<br>
<br>
<label>House type
<input type='text' name='houseType' id='houseType' placeholder="House type">
</label>
<br>
<br>
<label>House Floors:
<input type='text' name='houseFloors' id='houseFloors' placeholder="House Floors">
</label>
<br>
<br>
<label>House Location:
<input type='text' name='houselocation' id='houselocation' placeholder="House Location">
</label>
<br>
<br>
<div>
<label>search:
<input type="text" name="search" id="search-input" placeholder="search">
<input type="submit">
</div>
<button type="button" id="add">Add Details</button>
<button type="button" id="print">Show</button>
<pre></pre>
<script>
var list = [],
$ins = $('#houseName, #houseType, #houseFloors, #houselocation'),
var counter = {
houseName: {},
houseType: {},
houseFloors: {},
houselocation: {}
};
$('#add').click(function() {
var obj = {},
valid = true;
$ins.each(function() {
var val = this.value;
if (val) {
obj[this.id] = val;
} else {
alert(" Cannot be blank");
return false;
}
});
if (valid) {
list.push(obj);
$ins.val('');
}
});
$('#print').click(function() {
$('pre').text(JSON.stringify(list) + '\n\n');
})
var keyword = $('#search-input').val();
var filteredList = list.filter(function(user){
return user.houseName === 'man'; // Or u can use indexOf if u want check if the keyword is contained
});
</script>
</body>
</html>
You may use Array.prototype.filter.
In ur case it will look like
var filteredList = list.filter(function(user){
return user.houseName === 'man'; // Or u can use indexOf if u want check if the keyword is contained
});
If u would like to search it with an input box, there will be a little bit more work to do:
//The follow code should be executed when u are going to do the 'search' action
//It could be an click on a button, or just in a listener which is triggered when the search box fires 'change' events
//First u need to get the keyword from the search input box:
var keyword = $('#search-input').val();
//maybe do some value check
//if (keyword === '') return;
//then get the filtered List
var filteredList = list.filter(function(user){
return user.houseName === keyword;
});
//Finally update the UI based on the filtered List
//Maybe jQuery's DOM functions could be helpful
I'll be honest. I'm a teacher at a school in Japan, and I don't really have much of a programming background. I'm dabbling more than anything else, but I thought it might be fun to try to make an English name generator that the kids could use for an activity. The program works just fine if I have it return the result as an alert, but what I really want to do is update the value of the textarea so that it reflects the generated name rather than "Your Name Here". I've been pouring over forums for hours and don't quite understand why what I have doesn't work as many of the solutions I've seen for dynamically changing a textarea value all offer the same advice, which is to change it as follows.
function someFunction()
{
var x=document.getElementById("id for textarea")
x.value = "new value"
}
Warning: Hand-coded and probably wrought with errors.
<script type="text/javascript">
function name_gen()
{
var randomNum;
var form = document.getElementById("nameGenForm");
var result = document.getElementById("nameSpace");
var boyNames = new Array("Adam", "Ben", "Cory", "David", "Eric", "Frank", "George",
"Harry", "Isaac", "James", "Kevin", "Lance", "Matthew",
"Nathan", "Patrick", "Quincy", "Ryan", "Sean", "Terrance",
"Vincent", "William", "Xavier", "Zach");
var girlNames = new Array("Alice", "Beth", "Catherine", "Danielle", "Erika", "Holly",
"Isabelle", "Jenny", "Kristen", "Lisa", "Mary", "Naomi",
"Patricia", "Quinn", "Rhianna", "Sarah", "Tiffany", "Wendy");
if (form.male.checked == true)
{
randomNum = Math.floor(Math.random()*boyNames.length);
name = boyNames[randomNum];
}
else if (form.female.checked == true)
{
randomNum = Math.floor(Math.random()*girlNames.length);
name = girlNames[randomNum];
}
else
{
alert("Please make a selection.");
return false;
}
alert(name);
//result.value = name;
}
</script>
And here's the accompanying HTML.
<form id="nameGenForm" action="" method="post">
<fieldset>
<legend>Random Name Generator</legend>
<input id="male" name="sex" type="radio" />
<label for="male">Male</label>
<input id="female" name="sex" type="radio" />
<label for="female">Female</label><br />
<input type="submit" value="Generate" onclick="name_gen();" />
</fieldset>
</form>
<div id="textArea">
<textarea rows="1" cols="20" id="nameSpace" readonly>Your Name Here</textarea>
</div>
The problem is that your button is type="submit". If you change that to type="button", it will work. A submit button submits the page, in this case back to the same page, but it has the result of resetting to the default value.
It looks like your problem is that you have var x=getElementById('id for textarea") you should have var x= document.getElementById("id for textarea");
Also, its not .value its .innerHTML.
So that first snippet should be
function someFunction()
{
var x = document.getElementById("id for textarea")
x.value = "new value" //per #Tomalak's comment
}
+1 - for just dabbling in it its pretty good!