applying text input value to other empty text fields - jQuery - javascript

This question is in the continuation of another question I have asked earlier URL
I am generating rows dynamically and and all the fields are being populated using JS thus the input ID's for all text boxes are different. Now if a user enter some number on "Apply to all" input field and click the button the same number should be set to all the rows which are added in the betslip.
HTML structure where I am adding rows dynamically
<div id="bets">
<div id="idNo1" class="bet gray2" name="singleBet">
<div class="left">
<p class="title">
<p class="supermid">
<input id="input_1" type="text">
</div>
</div>
<div id="idNo2" class="bet gray2" name="singleBet">
<div class="left">
<p class="title">
<p class="supermid">
<input id="input_2" type="text">
</div>
</div>
<div id="idNo3" class="bet gray2" name="singleBet">
<div class="left">
<p class="title">
<p class="supermid">
<input id="input_3" type="text">
</div>
</div>
</div>
JS for adding element in the individual bets
BetSlip.prototype.createSingleBetDiv = function(Bet) {
var id = Bet.betType + '_' + Bet.productId + '_' + Bet.mpid,
divId = id + '_div';
// If such bet already exists
if (typeof document.betSlip.singleDivs[divId] == "undefined") {
var div = element.create('div'),
a = element.create('a'),
leftDiv = element.create('div'),
closeDiv = element.create('div'),
singleBetNumber = ++document.getElementsByName('singleBet').length;
element.setId(div, divId);
element.setName(div, 'singleBet');
element.setClassName(div, 'bet gray2');
element.setClassName(a, 'right orange');
element.setClassName(leftDiv, 'left');
element.setClassName(closeDiv, 'icon_shut_bet');
// Info abt the bet
$(leftDiv).append('<p class="title"><b><span class="bet_no">' + singleBetNumber + '</span>. ' + Bet['horseName'] + '</b></p>');
var raceInfo = "";
$("#raceInfo").contents().filter(function () {
if (this.nodeType === 3) raceInfo = $(this).text() + ', ' + Bet['betTypeName'] + ' (' + Bet['value'].toFixed(2) + ')';
});
$(leftDiv).append('<p class="title">' + raceInfo + '</p>');
// Closing btn
(function(id) {
a.onclick=function() {document.betSlip.removeSingleBet(divId);};
})(id);
$(a).append(closeDiv);
// Creating input field
$(leftDiv).append('<p class="supermid"><input id="' + id + '_input\" type="text"></p>');
// Creating WIN / PLACE checkbox selection
$(leftDiv).append('<p><input id="' + id + '_checkbox\" type="checkbox"><b>' + winPlace + '</b></p>');
// Append left part
$(div).append(leftDiv);
// Append right part
$(div).append(a);
// Appending div with data
$.data(div, 'Bet', Bet);
// Add div to the bet slip map
document.betSlip.singleDivs[divId] = div;
return div;
}
else {
$("#betSlipError").show();
$("#betSlipError").html(sameBet);
return null;
}
}
HTML for applyTOall button
<a onclick="document.betSlip.applyToAll(event)" class="button apply orange">APPLY TO ALL <input type="text"> </a>
JS for applyToall function
BetSlip.prototype.applyToAll = function(e) {
e.preventDefault();
document.betSlip.applyToAllBetInput($(this).find("input").val());
}
BetSlip.prototype.applyToAllBetInput = function(value) {
$("#bets div[name=singleBet] .supermid input:text").val(value);
}

Try doing this way:
$('yourbutton').on('click', function(){
var applyVal = $('applyvalinput').val();
$('#bets').find('[id^="input"][type="text"]').val(applyVal);
});//^------finds the inputs in this specific div.
Click your button and cache the value of your apply to all input val and check for the inputs which has the ids started [id^="input"] by the term input and it applies the value to each text input.

Related

How to show input value and label from a div

Goal: Show a label, and input value from a different div and display it in a different section
I have a div that dynamically generates a set of input fields, and I am trying to then display that input fields value and their corresponding labels in a different section.
For example:
Step 1 - User enters in the number 5 into an input field.
Step 2 - There are 5 input fields created (based on value entered from step 1). Those input fields are labeled #1, #2, #3, etc... all the way to #5 or whatever number the user entered in Step 1.
Step 3 - User is presented with a new HTML section that lists off the labels (#1, #2, #3, etc.) and next to the labels is the value the user entered for those corresponding input fields.
Here is the code created for Step 2:
<label>#' + count + '</label>
<input type="number" name="length_field" value="" class="form-control length_field" />
Then, I need some javascript/jquery to take the labels and their corresponding input values and display then something like this:
<p>[LABEL #1] <span>[LABEL #1 INPUT VALUE]</span></p>
<p>[LABEL #2] <span>[LABEL #2 INPUT VALUE]</span></p>
<p>[LABEL #3] <span>[LABEL #3 INPUT VALUE]</span></p>
Etc...
For step 2 you need to check the value of your length_field input and create that many inputs by JavaScript. Set some helper ID and CLASS attributes so you can get values later.
For step 3 use that attributes to get input field values and set them as result div's html.
$(document).on('change', '#length_field', function() {
var inputsCount = parseInt($(this).val());
$('#inputsWrapper').html('');
$('#result').html('');
for (var i = 1; i <= inputsCount; i++) {
// Create custom input with label
var tempInput = document.createElement('input');
tempInput.setAttribute('name', i);
tempInput.setAttribute('id', i);
tempInput.setAttribute('class', 'customInputs');
var tempInputLabel = document.createElement('label');
tempInputLabel.setAttribute("for", i);
tempInputLabel.innerHTML = 'Input #' + i + ": ";
$('#inputsWrapper').append(tempInputLabel);
$('#inputsWrapper').append(tempInput);
// Create corresponding value presenter in result div
var resultRow = document.createElement('p');
resultRow.setAttribute('id', 'result-' + i);
resultRow.innerHTML = 'Label #' + i + ':';
$('#result').append(resultRow);
}
});
$(document).on('keyup', '.customInputs', function() {
var id = $(this).attr('id');
var inputValue = $(this).val();
$('#result-' + id).html('Label #' + id + ': <span> ' + inputValue + '</span>');
});
#inputsWrapper input {
display: block;
margin-bottom: 10px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label for="length_field">Enter the number of inputs you want:</label>
<input type="number" name="length_field" id="length_field" />
<br/>
<div id="inputsWrapper">
</div>
<hr>
<div id="result">
</div>
This is really quick'n'dirty but it works.
I'm using a for-loop in both steps, in the first step the for-loop is generating the input fields and outputting them after.
In the second step I'm saving the html of the resulting paragraphs in a variable, because I can't override the document, because my wanted values are in the input fields.
The on keypress listener is optional and ensures that you don't have to press the Submit button with your mouse ;)
If I could help you i would appreciate if you could mark this answer as accepted.
let number = 0;
$(document).on("click", "#step1", function() {
number = $("input").val();
if (number > 0) {
let html = "", i;
for (i = 1; i <= number; i++) {
html += "<label for='input_" + i + "'>#" + i + "</label>: <input type='text' id='input_" + i + "'><br>";
}
html += "<button id='step2'>Submit</button>"
$("body").html(html);
}
})
$(document).on("click", "#step2", function() {
let html = "", i;
for (i = 1; i <= number; i++) {
html += "<p>Label #" + i + ": <span>" + $("#input_" + i).val() + "</span></p>";
}
$("body").html(html);
})
$(document).on('keypress', function(e) {
if (e.which == 13) {
$("button").trigger("click");
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="number" placeholder="Number of fields">
<button id="step1">Submit</button>

JavaScript function not getting called?

So I have a button that calls
<a class="btn btn-primary" id="btnAdd" href="#" onclick="ChangesJs.AddPlayList()"> <i class="fa fa-fw fa-plus fa-lg"></i>Add </a>
and the JS function creates additional form on its own.
function AddPlayList() {
var form = "<div class='form-group col-sm-3 clscommercial_" + addPlayList + "' style='display:none;' ><label>Break No.</label> <span class='red_color'>*</span><input class='form-control' id='txtBreakno_" + x + "' maxlength='2' onblur='ChangesJS.IsNumeric(this)' onchange='CommonJs.HideErrorMessage(this)' placeholder='Break No.' type='text'></div>";
This is the definition of IsNumeric function
function IsNumeric(selectinput) {
var _value = selectinput.value;
var ID = selectinput.id;
if (_value !== "" && !$.isNumeric(_value)) {
$("#div_" + ID).show();
$("#span_" + ID).html("Please Enter numeric value !");
selectinput.value = "";
selectinput.focus();
}
}
When I get of out focus in the text field no validation is shown.
The elements created in the dom after initial load need to have an event listener added.
function AddPlayList() {
var form = "<div class='form-group col-sm-3 clscommercial_" + addPlayList + "' style='display:none;' ><label>Break No.</label> <span class='red_color'>* </span><input class='form-control' id='txtBreakno_" + x + "' maxlength='2' onblur='ChangesJS.IsNumeric(this)' placeholder='Break No.' type='text'></div>";
// append it to the DOM....
var element = document.getElementsByClassName("clscommercial_" + addPlayList);
element.addEventListener('change', function() {
CommonJs.HideErrorMessage(this);
}, false);
}
Also, don't forget to remove the listener if you remove the element it you may end up having it fire multiple times.
The jQuery way handles this well if your using it.
$('body').on('change', '.clscommercial', function() {
// This will fire even on elements added programmatically as long
// as your top selector is (body) was created on page load.
CommonJs.HideErrorMessage($(this)[0]);
)};

Reset text using jQuery, with AJAX call present

I am currently practicing making Ajax calls using jQuery. The user enters in a country, presses the Search button, and the AJAX call is made to the API. The user then sees random facts displayed about the country they searched for.
My problem is that I want to allow the user to reset the form, and the facts automatically disappear. I got up to this point, but when I enter in a second country, the facts don't want to pop up anymore.
I should also mention that I'm using css.animate to animate a few elements on the page. I wonder if that might be messing things up. Can anyone help me out here? I would really like to put the finishing touches on this simple website.
Here's my HTML:
<h1 class = "animated infinte bounce"> World Facts </h1>
<div class = "info">
<p> Enter in a country to get some information about it! </p>
<form class = "zipform">
<input type ="text" class = "pure-input-rounded">
<button type = "submit" class = "pure_button"> Search </button>
<input type="reset" value="Reset">
</form>
<div class = "world_facts">
<p id = "region"> </p>
<p id = "capital"> </p>
<p id = "people"> </p>
<p id = "nat_name"> </p>
<p id = "domain"> </p>
</div>
</div>
And my JS/jQuery:
`$('.pure_button').click(function(e) {
e.preventDefault()
console.log("click noticed")
$.ajax({
url: //API URL HERE,
type: "GET",
success: function(data) {
var country = $('.pure-input-rounded').val();
console.log("This works too")
debugger
console.log(data)
var capital = data[0].capital
var people = data[0].demonym
var region = data[0].region
var nat_name = data[0].nativeName
var domain = data[0].topLevelDomain
$('.world_facts').addClass("animated fadeInDown")
$('#region').text(country + " is located in " + region + ".")
$('#capital').text("Its capital is " + capital + ".")
$('#people').text("People from " + country + " are called " + people + ".")
$('#nat_name').text(people + " people call their country " + nat_name + ".")
$('#domain').text("Websites registered in " + country + " have the top level domain name of " + domain + ".")
}
});
});
$(":reset").click(function(e) {
e.preventDefault()
$(".zipform")[0].reset()
console.log("Form reset")
$(".world_facts").text("")
});`
Because when you call
$(".world_facts").text("")
You are removing all the children elements so they no longer exist. You need to remove the text from the children.
$(".world_facts p").text("")
Don't use .text("") upon the div, since you lose all the elements within. Besides, you can use .empty().
So, change the line to: $(".world_facts p").empty();
Here's an example:
http://jsbin.com/didumiyexi/1/edit
By doing $(".world_facts").text("") you aren't removing text from all individual nodes inside that element but (as intended) you basically remove the entire content of what's inside that particular div
You can reset it in the following way instead:
$('.world_facts > p').text("");
This selector targets every immediate <p> inside the world_facts container and sets its text to blank
example:
$('.pure_button').click(function(e) {
e.preventDefault()
console.log("click noticed")
var data = [{
capital: 'London',
demonym: 'British',
region: 'Europe',
nativeName: 'UK',
topLevelDomain: 'co.uk'
}];
var country = $('.pure-input-rounded').val();
var capital = data[0].capital
var people = data[0].demonym
var region = data[0].region
var nat_name = data[0].nativeName
var domain = data[0].topLevelDomain
$('.world_facts').addClass("animated fadeInDown")
$('#region').text(country + " is located in " + region + ".")
$('#capital').text("Its capital is " + capital + ".")
$('#people').text("People from " + country + " are called " + people + ".")
$('#nat_name').text(people + " people call their country " + nat_name + ".")
$('#domain').text("Websites registered in " + country + " have the top level domain name of " + domain + ".")
});
$(":reset").click(function(e) {
e.preventDefault();
$(".zipform")[0].reset();
// instead, clear each form separately
$('.world_facts > p').text("");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<h1 class="animated infinte bounce"> World Facts </h1>
<div class="info">
<p>Enter in a country to get some information about it!</p>
<form class="zipform">
<input type="text" class="pure-input-rounded">
<button type="submit" class="pure_button">Search</button>
<input type="reset" value="Reset">
</form>
<div class="world_facts">
<p id="region"></p>
<p id="capital"></p>
<p id="people"></p>
<p id="nat_name"></p>
<p id="domain"></p>
</div>
</div>

passing/displaying values from JavaScript to HTML page

I have the following JS code which use's local storage to display the 'name' and 'age' entered previously:
This HTML code currently displays the date, time, name and age of a person in a table. how can i pass these values to be displayed in a HTML form as labels instead of in that table?
HTML only bringing back the start time, name and age aren't being displayed:
<div id="history_list"></div>
<div id="name"> </div>
<div id="age"></div>
JS:
function loadHistoryList() {
for(var i = numberOfHistory; i >= 1; i--) {
var historyData = new historyElement(db.getItem(i.toString()));
if(historyData === null) {
console.error('error');
continue;
}
$('#history_list').append(historyData.startTime);
$('#name').append(historyData.name);
$('#age').append(historyData.age);
}
}
instead of
var div = '<div id="history_element"><div id="element_title">' + historyData.startDate + ' ' + historyData.startTime + '</div><table>';
var div = '<div id="name"><tr><td>name: </td><td>' + historyData.name+ '</td></tr>';
var div = '<div id="age"><tr><td>age: </td><td>' + historyData.age+ '</td></tr>';
div += '</table></div>';
$('#history_list').append(div);
$('#name').append(div);
$('#age').append(div);
Do this:
$('#history_list').append(historyData.startTime);
$('#name').append(historyData.name);
$('#age').append(historyData.age);
In short: you can (and should in this case) simply add the desired value to the container (the DIV, Form field, or whatnot)
those three lines starting witn var div (...) are overwriting each previous line, but that is a side note.
Overall, you should read up more on JavaScript and/or JQuery.
To populate the form field First you have to add a form element like input field
HTML
<div id="history_list">
</div>
<input type="text" id="name" name="name">
JS
function loadHistoryList() {
for(var i = numberOfHistory; i >= 1; i--) {
var historyData = new historyElement(db.getItem(i.toString()));
if(historyData === null) {
console.error('error');
continue;
}
$('#name').val(historyData.name);
}
}

Button Group Click Handler - How to get text content of clicked button?

I am trying to set up two button groups. A click on any button in the second group should add a new button to the first group. The new button shall get the same label as the clicked button.
var name = this.textContent works if the click handler is attached to a single button. How do you get the text content of the clicked button when the click handler is instead attached to a group of buttons?
HTML:
<body>
<div id="group1">
<button> nameA </button>
<button> nameB </button>
</div>
<hr>
<div id="group2">
<button> nameC </button>
<button> nameD </button>
</div>
</body>
Javascript:
$('#group2').on('click', function(event) {
var name = this.textContent // wrong!
var r = $('<input type="button" value="' + name + '">');
$("div#group1").append(r);
});
JSFiddle Demo
Use event delegation:
$('#group2').on('click', 'button', function(event) {
var name = this.textContent
var r = $('<input type="button" value="' + name + '">');
$("div#group1").append(r);
});
Second parameter in 'on' method can be selector string to filter the descendants of the selected elements that trigger the event.
Check this https://jsfiddle.net/q6b6g3xm/
In your case, this should be enought:
$('#group2 button').click(function(event) {
var name = this.textContent
var r = $('<input type="button" value="' + name + '">');
$("div#group1").append(r);
});
Prefer the RobHil solution if you other buttons will be created in #group2 after the execution of the jQuery code.
Else, I see two other possibilities:
$('#group2 button').each(function () {
var $button = $(this).click(function(event) {
var r = $('<input type="button" value="' + $button.text() + '">');
$("div#group1").append(r);
});
});
or:
$('#group2').click(function(event) {
var $button = $(event.target);
var r = $('<input type="button" value="' + $button.text() + '">');
$("div#group1").append(r);
});
But keep in mind the target depend on where you click if you have nested blocks in the clicked zone: https://api.jquery.com/event.target/
Here is my own approach to the problem. I modified HTML code a little by adding individual id to the buttons.
HTML:
<div id="group1" >
<button id="btn-A">nameA</button>
<button id="btn-B">nameB</button>
<button id="btn-C">nameC</button>
</div>
<hr />
<div id="group2">
<button id="btn-D">nameD</button>
<button id="btn-E">nameE</button>
<button id="btn-F">nameF</button>
</div>
JavaScript:
// click on the button
$(document).on('click','button', function(){
//store the value of the id and
// split it # '-' into array ['btn','A']
$id = $(this).attr('id').split('-');
// store the value at index 1 into $id
$id = $id[1];
//get the Id of the current div group
$divId = $(this).closest('div').attr('id');
//check which div group is current and
//Assign the reversed value as appropriate
if($divId === "group1"){
$addId = "#group2";
}else {
$addId = "#group1";
}
//Remove the button from the group
$(this).remove();
//Add the button to the second div group
$($addId).append('<button id="btn-'+$id+'">'+$(this).text()+'</button>');
});

Categories