how can I call tab key event in javascript - javascript

Here is my simple data
John Smith Individual 010987654
I have three textboxes and the above data will automatically insert in the first textbox of my web page.
My problem is
How can I make as soon as data is inserted in the textbox (means when textbox’s onchange event is fired)
First, javascript will find ‘tab’ space in this string
Second, if find ‘tab’ space in the string, javascript will press ‘tab’ key and insert data in the another text box.

Here's a plain old DOM-0 JavaScript solution, just for fun.
document.getElementById('the_form').onchange = function() {
var field = this[0];
var parts = field.value.split('\t');
for (var i = 0; field = this[i]; i++) {
field.value = parts[i] || '';
}
}
http://jsfiddle.net/vKaxP/

I thought you want to split those texts into different textboxes, so I got something like:
$("#a").change(function(){
var s = $(this).val();
if (s.match(/\t+/)) {
var a = s.split(/\t+/);
$('#a').val(a[0]);
$('#b').val(a[1]);
$('#c').val(a[2]);
}
});
if you type a b c into the first input box, press tab or enter, b and c would appear into other textboxes, repectively.
I use \s(space) for test in jsfiddle. You could just change it to \t for tab.

Here is prototype of what you need to do.
HTML:
<div>
<input id="a" />
</div>
<div>
<input id="b" />
</div>
JavaScript:
$('#a').on('change', function () {
var value = $(this).val();
// Test if string has a tab:
if (/\t/.test(value)) {
// Just set the value of the other text box
// And set focus:
// Using jQuery that would be:
$('#b').val(value).focus();
}
});
Working demo: http://jsfiddle.net/tkirda/XmArP/

If I correctly understand the question as "The server puts all the data into one field, tab separated, and I want to split it up into several textfields", then try this:
On load:
var fields = [$("#firstField"), $("#secondField"), $("#thirdField")];
var data = fields[0].val().split(/\t/);
for (var i = 0; i < 3; i++) {
fields[i].val(data[i]);
}

Related

Search a word in XML and display that node only using javascript

I have created a input text and submit button in HTML page.
In the HTML page,
Question 1: if I type "WHAT is animal" and click submit, then i need a js alert should show "lion, tiger, elephant, dog, cat"
Question 2: if type " what are pet animals" and click submit, then I need a js alert should show dog, cat only.
<database>
<content>
<keywords><![CDATA[wild animal]]></keywords>
<description><![CDATA[ lion, tiger, elephant]]></description>
</content>
<content>
<keywords><![CDATA[pet animal]]></keywords>
<description><![CDATA[dog, cat]]></description>
</content>
</database>
I had nothing else to do, so I went ahead and wrote a functional script. Explanation can be found in the comments of the code.
/* XML String */
const XMLString = '<database>'+
'<content>'+
'<keywords><![CDATA[wild animal]]></keywords>'+
'<description><![CDATA[ lion, tiger, elephant]]></description>'+
'</content>'+
'<content>'+
'<keywords><![CDATA[pet animal]]></keywords>'+
'<description><![CDATA[dog, cat]]></description>'+
'</content>'+
'</database>';
/* Search function */
function searchXML(searchString){
const parser = new DOMParser();
// Parse XML string with the DOM parser
const xmldoc = parser.parseFromString(XMLString,"text/xml");
// Get all content tags
const contentEles = xmldoc.getElementsByTagName("content");
// Empty array to save result
let result = [];
// Loop through each content element
for(let i = 0; i < contentEles.length; i++){
// Get the keywords inside the keywords element
const keywords = contentEles[i].childNodes[0].textContent.split(" ");
// Loop through each keyword
for(let y = 0; y < keywords.length; y++){
// Create regex that matches whole words only
const keyword = '\\b'+keywords[y]+'\\b';
const regex = new RegExp(keyword,"i");
// Search the searchString if it contains a keyword
if(searchString.search(regex) !== -1){
// Push the contents of the description element to the result
// array if a keyword was found
result.push(contentEles[i].childNodes[1].textContent);
}
}
}
// Convert the result array to a string and alert it
alert(result.join());
}
/* Add event listener to html document fully loaded */
document.addEventListener("DOMContentLoaded", function(event){
const form = document.getElementById('search');
/* Add event listener to form submit */
form.addEventListener("submit", function(e){
// Prevent form from submitting
e.preventDefault();
// Perform search
searchXML(document.getElementById('searchXML').value);
// Empty the form
form.reset();
});
});
<form id="search">
<label>Search: </label>
<input type="text" id="searchXML"/>
<input type="submit" value="Search"/>
</form>
JSAnimalName: function myFunction() {var l_animal = document.getElementById("animal").value;
if('WHAT is animal'==l_animal){alert('lion, tiger, elephant, dog, cat'); }else if('what are pet animals'==l_animal){alert('dog, cat');}else{alert('Wrong input'); }}

`Dynamically populate a dropdown menu using strings from a textarea

I want this coded in jquery preferably but normally, javascript is still fine by me.
The question is this:
I have a textarea and a dropdown menu on thesame page.
I can fill in text into the textarea by typing it or pasting it. The textarea on eachline contain emails and names seperated by comma.: Eg
email1#xyz.com, Richards Dough
email2#abc.com
EmilY34#yahoo.com , Emily Whites
Juniorpope4u#gmail.com , Junior
Mike87#yahoo.co.uk,
Ademola45thus#gmail.com, Ademola Erickson
etc
(notice the comma can be anywhere or even absent)
I want the dropdown menu to automatically be filled with the values of domain names of emails found on the textarea.
NOTE: There should NOT be duplicate listing in the dropdown and the listing should be alphabetically arranged in the dropdown
In my example, the dropdown will be be populated as below:
ALL
abc.com
gmail.com
xyz.com
yahoo.com
yahoo.co.uk
Default selected dropdown item has a value of ALL.
Please I know how to do this in php but have no clue about using javascript or jquery. Plus php have to refresh page to work but javascript wouldn't need page reloading
Hi Kindly check https://jsfiddle.net/pykmgyyt/5/ ...
jQuery
$(document).ready(function(){
var arr= new Array();
arr[0]="ALL"; //Setting fist element of the array to ALL
$('.btnUpdate').on('click', function(){
var newEmails=new Array();
var newEmails=$('.taEmails').val().split(/[ ,\r\n]+/); // get text area value and split text whenever jq encounters comma, space or newline and storing it into an array
/* Travese through newEMails array and push string which contains '#' in to arr array */
$.each(newEmails, function(i){
if (newEmails[i].indexOf('#') > -1){
arr.push(newEmails[i].substring(newEmails[i].indexOf("#") + 1)); /* Get only the domain names*/
console.log(newEmails[i]);
}
});
// check for duplicates
var result = [];
$.each(arr, function(i, e) {
if ($.inArray(e, result) == -1) result.push(e);
});
arr= result;
$('.ddEmails').empty(); // Empty dropdown
arr.sort(); // sort array
/*Append new array*/
$.each(arr, function(i){
$('.ddEmails').append("<option>"+arr[i]+"</option>");
//console.log(arr[i]);
}); /// arr each
}); // click
});
-split by comma and newline
-loop through each splited string
check whether it has # symbol
Find the domain and return
-display it in the select box
HTML
<textarea id="emails" onkeyup="finddomain();">
email1#xyz.com, Richards Dough
email2#abc.com
EmilY34#yahoo.com , Emily Whites
Juniorpope4u#gmail.com , Junior
Mike87#yahoo.co.uk,
Ademola45thus#gmail.com, Ademola Erickson
</textarea>
<select id="add_domain" name="add_domain">
</select>
Javascript
<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="//code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
<script type="text/javascript">
function extractDomain(url) {
var ind=url.indexOf("#");
if (ind > 0)
{
var domain = url.substr((ind+1));
return domain;
}
else
return '';
}
function finddomain()
{
// You can do the below parts on javascript event
data = document.getElementById('emails').value;
var arr = data.split(/[\n,]+/); //data.split('\n');
var arrayLength = arr.length;
var sel = document.getElementById("add_domain");
for (var i = 0; i < arrayLength; i++) {
var domain = extractDomain(arr[i].trim());
if (domain != '' && $("#add_domain option[value='"+domain+"']").length == 0)
{
var option = document.createElement("option");
option.text = domain;
option.value = domain;
sel.appendChild(option);
}
}
}
</script>
Below part is to extract domains for multiple events
<script type="text/javascript">
$(document).ready(function() {
$('#emails').on('keyup keypress blur change', function(e) {
// e.type is the type of event fired
finddomain();
});
});
</script>

Store values from dynamically generated text boxes into array

I'm creating a Time table generating website as a part of my project and I am stuck at one point.
Using for loop, I am generating user selected text boxes for subjects and faculties. Now the problem is that I cannot get the values of those dynamically generated text boxes. I want to get the values and store it into array so that I can then later on store it to database
If I am using localstorage, then it sometimes shows NaN or undefined. Please help me out.
Following is my Jquery code
$.fn.CreateDynamicTextBoxes = function()
{
$('#DynamicTextBoxContainer, #DynamicTextBoxContainer2').css('display','block');
InputtedValue = $('#SemesterSubjectsSelection').val();
SubjectsNames = [];
for (i = 0; i < InputtedValue; i++)
{
TextBoxContainer1 = $('#DynamicTextBoxContainer');
TextBoxContainer2 = $('#DynamicTextBoxContainer2');
$('<input type="text" class="InputBoxes" id="SubjectTextBoxes'+i+'" placeholder="Subject '+i+' Name" style="margin:5px;" value=""><br>').appendTo(TextBoxContainer1);
$('<input type="text" class="InputBoxes" id="FacultyTextBoxes'+i+'" placeholder="Subject '+i+' Faculty Name" style="margin:5px;" value=""><br>').appendTo(TextBoxContainer2);
SubjectsNames['SubjectTextBoxes'+i];
}
$('#DynamicTextBoxContainer, #UnusedContainer, #DynamicTextBoxContainer2').css('border-top','1px solid #DDD');
}
$.fn.CreateTimeTable = function()
{
for (x = 0; x < i; x++)
{
localStorage.setItem("Main"+x, +SubjectsNames[i]);
}
}
I am also posting screenshot for better understanding
I understand you create 2 text boxes for each subject, one for subject, and second one for faculty. And you want it as a jQuery plugin.
First of all, I think you should create single plugin instead of two, and expose what you need from the plugin.
You should avoid global variables, right now you have InputtedValue, i, SubjectsNames, etc. declared as a global variables, and I believe you should not do that, but keep these variables inside you plugin and expose only what you really need.
You declare your SubjectNames, but later in first for loop you try to access its properties, and actually do nothing with this. In second for loop you try to access it as an array, but it's empty, as you did not assign any values in it.
Take a look at the snippet I created. I do not play much with jQuery, and especially with custom plugins, so the code is not perfect and can be optimized, but I believe it shows the idea. I pass some selectors as in configuration object to make it more reusable. I added 2 buttons to make it more "playable", but you can change it as you prefer. Prepare button creates your dynamic text boxes, and button Generate takes their values and "print" them in result div. generate method is exposed from the plugin to take the values outside the plugin, so you can do it whatever you want with them (e.g. store them in local storage).
$(function() {
$.fn.timeTables = function(config) {
// prepare variables with jQuery objects, based on selectors provided in config object
var numberOfSubjectsTextBox = $(config.numberOfSubjects);
var subjectsDiv = $(config.subjects);
var facultiesDiv = $(config.faculties);
var prepareButton = $(config.prepareButton);
var numberOfSubjects = 0;
prepareButton.click(function() {
// read number of subjects from the textbox - some validation should be added here
numberOfSubjects = +numberOfSubjectsTextBox.val();
// clear subjects and faculties div from any text boxes there
subjectsDiv.empty();
facultiesDiv.empty();
// create new text boxes for each subject and append them to proper div
// TODO: these inputs could be stored in arrays and used later
for (var i = 0; i < numberOfSubjects; i++) {
$('<input type="text" placeholder="Subject ' + i + '" />').appendTo(subjectsDiv);
$('<input type="text" placeholder="Faculty ' + i + '" />').appendTo(facultiesDiv);
}
});
function generate() {
// prepare result array
var result = [];
// get all text boxes from subjects and faculties divs
var subjectTextBoxes = subjectsDiv.find('input');
var facultiesTextBoxes = facultiesDiv.find('input');
// read subject and faculty for each subject - numberOfSubjects variable stores proper value
for (var i = 0; i < numberOfSubjects; i++) {
result.push({
subject: $(subjectTextBoxes[i]).val(),
faculty: $(facultiesTextBoxes[i]).val()
});
}
return result;
}
// expose generate function outside the plugin
return {
generate: generate
};
};
var tt = $('#container').timeTables({
numberOfSubjects: '#numberOfSubjects',
subjects: '#subjects',
faculties: '#faculties',
prepareButton: '#prepare'
});
$('#generate').click(function() {
// generate result and 'print' it to result div
var times = tt.generate();
var result = $('#result');
result.empty();
for (var i = 0; i < times.length; i++) {
$('<div>' + times[i].subject + ': ' + times[i].faculty + '</div>').appendTo(result);
}
});
});
#content div {
float: left;
}
#content div input {
display: block;
}
#footer {
clear: both;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="container">
<div id="header">
<input type="text" id="numberOfSubjects" placeholder="Number of subjects" />
<button id="prepare">
Prepare
</button>
</div>
<div id="content">
<div id="subjects">
</div>
<div id="faculties">
</div>
</div>
</div>
<div id="footer">
<button id="generate">Generate</button>
<div id="result">
</div>
</div>

Eloquent JS Exercise (Ch.18 Q. 2)

I was hoping someone can help me figure out what I'm doing wrong... There's this exercise in the Eloquent JS book that asks you to write some code that can suggest words/values to users as they type... The code I've written is below. What happens is that when I run the code, the div element's text content changes to the wrong value. Specifically, it's set to a string of all the elements inside the array 'terms'. I really cant figure out why this happens!
<input type="text" id="field">
<div id="suggestions" style="cursor: pointer"></div>
<script>
// Builds up an array with global variable names, like
// 'alert', 'document', and 'scrollTo'
var terms = [];
for (var name in window)
terms.push(name);
var input = document.querySelector('input');
var div = document.querySelector('#suggestions');
input.addEventListener("input", function(event){
var last = input.value.lastIndexOf(" ")+1;
var check = input.value.slice(last);
var reg = new RegExp(check);
for (var i=0; i<terms.length; i++) {
if (reg.test(terms[i])) {
var text = document.createTextNode(terms[i]);
div.appendChild(text)};
};
})
</script>
I guess you forgot to clean the div before each change in the input.
I also added a space after each word to make the output more readable.
// Builds up an array with global variable names, like
// 'alert', 'document', and 'scrollTo'
var terms = [];
for (var name in window)
terms.push(name);
var input = document.querySelector('input');
var div = document.querySelector('#suggestions');
input.addEventListener("input", function(event){
div.innerHTML = '';
var last = input.value.lastIndexOf(" ")+1;
var check = input.value.slice(last);
var reg = new RegExp(check);
for (var i=0; i<terms.length; i++) {
if (reg.test(terms[i])) {
var text = document.createTextNode(terms[i] + ' ');
div.appendChild(text)};
};
})
<input type="text" id="field">
<div id="suggestions" style="cursor: pointer"></div>
With this code, you will display the name of the properties from the window object that contains the last word from the input. Try it writting "window location document". Is it what you are looking for?

In Jquery take a different values from single text box id

I am using Data Table in jquery. So i passed one input type text box and passed the single id. This data table will take a multiple text box. i will enter values manually and pass it into the controller. I want to take one or more text box values as an array..
The following image is the exact view of my data table.
I have marked red color in one place. the three text boxes are in same id but different values. how to bind that?
function UpdateAmount() {debugger;
var id = "";
var count = 0;
$("input:checkbox[name=che]:checked").each(function () {
if (count == 0) {
id = $(this).val();
var amount= $('#Amount').val();
}
else {
id += "," + $(this).val();
amount+="," + $(this).val(); // if i give this i am getting the first text box value only.
}
count = count + 1;
});
if (count == 0) {
alert("Please select atleast one record to update");
return false;
}
Really stuck to find out the solution... I want to get the all text box values ?
An Id can only be used once; use a class, then when you reference the class(es), you can loop through them.
<input class="getValues" />
<input class="getValues" />
<input class="getValues" />
Then, reference as ...
$(".getValues")
Loop through as ...
var allValues = [];
var obs = $(".getValues");
for (var i=0,len=obs.length; i<len; i++) {
allValues.push($(obs[i]).val());
}
... and you now have an array of the values.
You could also use the jQuery .each functionality.
var allValues = [];
var obs = $(".getValues");
obs.each(function(index, value) {
allValues.push(value);
}
So, the fundamental rule is that you must not have duplicate IDs. Hence, use classes. So, in your example, replace the IDs of those text boxes with classes, something like:
<input class="amount" type="text" />
Then, try the below code.
function UpdateAmount() {
debugger;
var amount = [];
$("input:checkbox[name=che]:checked").each(function () {
var $row = $(this).closest("tr");
var inputVal = $row.find(".amount").val();
amount.push(inputVal);
});
console.log (amount); // an array of values
console.log (amount.join(", ")); // a comma separated string of values
if (!amount.length) {
alert("Please select atleast one record to update");
return false;
}
}
See if that works and I will then add some details as to what the code does.
First if you have all the textbox in a div then you get all the textbox value using children function like this
function GetTextBoxValueOne() {
$("#divAllTextBox").children("input:text").each(function () {
alert($(this).val());
});
}
Now another way is you can give a class name to those textboxes which value you need and get that control with class name like this,
function GetTextBoxValueTwo() {
$(".text-box").each(function () {
alert($(this).val());
});
}

Categories

Resources