Bind onlick events on several links - javascript

I am currently working on a solution for an application that is written in PHP, but needs a JS solution for a preview link and I am stuck with binding onclick-events on the links. The HTML is given and may not be changed. (so no adding of classes and stuff, even though that would be easier)
My initial thought was to just get each of the li and perform a callable that sets the event and defines the rules for what happens, when the link is clicked.
I am unsure what is the best possible solution to get the values of the two Inputs, belonging to the preview link, as while I was running the code mentioned above on what ever link I clicked, the last item was logged.
So basically this is 2 questions in one:
1. how to properly bind the click events.
2. how to best acces the inputs belonging to the link
var items = $('div.foobar').find('li');
items.each(function() {
this = $(this);
url = lo_this.find('a').attr('href');
this.find('a').click(function(event) {
event.preventDefault();
console.log(this)
/** here is the point, where I got stuck **/
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="foobar">
<li>
Link
<div class="justaname">
<input type="text" name="somenamewith[ID][foo]" value="">
<input type="text" name="somenamewith[ID][bar]" maxlength="50" value="">
</div>
</li>
<li>
Link
<div class="justaname">
<input type="text" name="somenamewith[OTHERID][foo]" value="">
<input type="text" name="somenamewith[OTHERID][bar]" maxlength="50" value="">
</div>
</li>
</div>

You mean this?
Assuming your inputs are in the same LI as the anchor
Ignoring the ID of the anchor and just getting the inputs in the same LI
Other code is needed if you want to use the ID of the link to access the named links
$('div.foobar li a').on("click",function(e) {
e.preventDefault();
$(this).closest("li").find("input").each(function() {
console.log(this.name,this.value)
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="foobar">
<li>
Link
<div class="justaname">
<input type="text" name="somenamewith[ID][foo]" value="">
<input type="text" name="somenamewith[ID][bar]" maxlength="50" value="">
</div>
</li>
<li>
Link
<div class="justaname">
<input type="text" name="somenamewith[OTHERID][foo]" value="">
<input type="text" name="somenamewith[OTHERID][bar]" maxlength="50" value="">
</div>
</li>
</div>

You can do this to bind click events to your links and then do whatever with the input elements contained by the div after the clicked link:
$('.foobar li a').on('click',function(event){
event.preventDefault();
$(this).next().find('input').each(function(){
//Whatever you want to do for each input
});
});

Related

copy text into field using radio selection

I am wanting to create the following using CSS, HTML and JavaScript
Course1 //dropdown selection//
....
Course2 //dropdown selection//
.....
WINNER
(RADIO checked for Course1) OR (RADIO clicked for Course2)
//automatically populated from either Course1 or Course2 depending on Radio checked//
but my dropdown selection and radio selection hamper each other.
When I have the name from the radio the same "winnerselected" the radio works, but the copying from the course1 or course2 doesn't work.
Maybe someone has created code like this somewhere else and knows how to get around it?
Any assistance will be appreciate.
code as follows:
<!--Make sure the form has the autocomplete function switched off:-->
<form autocomplete="off" action="/action_page.php">
<div class="autocomplete" style="width:300px;">
Course 1
<input id="myInput" type="text" name="golfcoursename1" placeholder="Golf
Course">
<form autocomplete="off" action="/action_page.php">
<div class="autocomplete" style="width:300px;">
Course 2
<input id="myInput1" type="text" name="golfcoursename2" placeholder="Golf
Course">
</div>
<p>
WINNER
<p>
<input type="radio" id="Course1" name="winnerselected" value="Course1"
onclick="FillWinner(this.form)">
<label for="Course1">Course 1</label>
<input type="radio" id="Course2" name="winnerselected" value="Course2"
onclick="FillWinner2(this.form)">
<label for="Course2">Course 2</label><br>
<input type="text" id="winner" name="Winner" placeholder="Winner">
<p>
</p>
<input type="submit">
</form>
<script>
function FillWinner(f) {
if(f.winnerselected.checked == true) {
f.winner.value = f.golfcoursename1.value;
if(f.winnerselected.checked == true)
f.winner.value = f.golfcoursename2.value;
}}
</script>
First, your HTML is not valid as you have a second form, with no closing tag, nested in the first one. Also, while is is legal to not close a p element, you really should for clarity sake.
Next, remove inline styles and inline JavaScript from your HTML. It just clutters up the code, causes redundancy, and is harder to read and maintain. Instead break your work into HTML, CSS, and JavaScript sections.
It's not clear what you exactly want, but my guess is that whichever radio button is clicked should dictate which textbox value becomes the winner. Based on that, see the comments inline below for a description of how the code works.
.autocomplete { width:300px; }
<!--Make sure the form has the autocomplete function switched off:-->
<form autocomplete="off" action="/action_page.php">
<div class="courses">
<div class="autocomplete">
Course 1 <input id="myInput" name="golfcoursename1" placeholder="Golf Course">
</div>
<div class="autocomplete">
Course 2 <input id="myInput1" name="golfcoursename2" placeholder="Golf Course">
</div>
</div>
<p>WINNER</p>
<p id="radioContainer">
<input type="radio" id="Course1" name="winnerselected" value="Course1">
<label for="Course1">Course 1</label>
<input type="radio" id="Course2" name="winnerselected" value="Course2">
<label for="Course2">Course 2</label><br>
<input type="text" id="winner" name="Winner" placeholder="Winner">
</p>
<input type="submit">
</form>
<script>
// Don't use inline HTML event attributes like onclick.
// Separate your JavaScript from your HTML
// Get references to the element(s) you'll need to work with
// Get all the elements that have a name attribute that starts with "golfcoursename"
const courseNames = document.querySelectorAll("[name^='golfcoursename']");
// Get all the elements that have a name attribute that is exactly "winnerselected"
const radioButtons = document.querySelectorAll("[name='winnerselected']");
const winner = document.getElementById("winner");
// Here's how to set up events in JS
const radCont = document.getElementById("radioContainer").addEventListener("click", fillWinner);
function fillWinner(event) {
// Look at the radiobuttons collection and get the index of the selected radio button from it.
const indexOfTextbox = Array.from(radioButtons).indexOf(event.target);
// Set the value of the winner textbox to textbox with the same index as the clicked radio button
winner.value = courseNames[indexOfTextbox].value;
}
</script>

Clear one text box or a div after writing something in another

I have two text boxes or two divs with same class ,and I want to clear first textbox after writing something in the second. How can I do this??
<html>
<body>
<div class="school">
First <input class="abc" type="text" name="first">
<br><br>
Second <input class="abc" type="text" name="second">
</div>
</body>
</html>
Check this code using input event.
https://api.jquery.com/on/
If the second input has an input event, the first input will be
empty.
$('input[name="second"]').on('input', function(){
$('input[name="first"]').val('')
})
$('input[name="second"]').on('input', function(){
$('input[name="first"]').val('')
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<body>
<div class="school">
First <input class="abc" type="text" name="first">
<br><br>
Second <input class="abc" type="text" name="second">
</div>
</body>
</html>
You can use .change() jQuery function to check if second textfield has changed or not. On change you can write code to clear first textbox
Html Code
<input type="text" name="text1" id="text1">
<input type="text" name="text2" id="text2">
JQuery Code
$(document).ready(function(){
$('#text2').change(function(){
$('#text1').val('');
});
});
Here is the fiddle
document.getElementsByName("first")[0].addEventListener("blur", function (){
document.getElementsByName("second")[0].value = "";
})
document.getElementsByName("second")[0].addEventListener("blur", function (){
document.getElementsByName("first")[0].value = "";
})
Note : if you want to to clear other input when you click on an input field then use focus event and if you want to clear other input when user changes input value then use change event or keypress event as per your requirement

jQuery remove selected element, dynamically generated

I have a form and I can dynamically add more lines but if I try to remove a specific line it does not work, however the first line gets removed with no problem.
Here is the html:
<form class="order-form">
<div class="product-lines">
<!-- Product Line Section -->
<div class="product-line">
<img alt="remove" src="img/close.png" />
<input class="input-text" name="product-code" type="text" placeholder="Product Code" ></input>
<input class="input-text" name="product-quantity" type="text" placeholder="Quantity"></input>
<input class="input-text" name="product-discript" type="text" placeholder="Discription of Product"></input>
<label class="label-sign">£</label>
<input class="input-text" name="product-price" type="text" placeholder="RRP Price"></input>
<br>
</div>
</div>
<div id="product-btn">
<input name="btn-add-line" type="button" value="Add new line"></input>
<input name="btn-update" type="button" value="Update"></input>
<input name="btn-submit" type="submit" value="Submit Order"></input>
<label class="label-sign">£</label>
<input class="input-text" name="order-info" type="text" placeholder="Order total" ></input>
</div>
</form>
The jQuery code I have tried:
$(".btn-close").on("click", function(e){
$(e.currentTarget).parent().remove();
});
I've also Tried
$(e.currentTarget).parents("div.product-lines).next("div.product-line).remove();
Any help would be most appreciated, also a explanation would be very helpful for me to learn.
Try something like
$(".product-lines").on("click", ".btn-close", function(e){
$(e.currentTarget).parent().remove();
});
You cannot attach events to objects that are not currently on page (lines).
You have to attach click event on product-lines object and when it is clicked you delegate event to "closest" product-line object!
You will need to changed the jQuery slightly to allow for Event Delegation. This means all elements added in future will get the event attached to them too.
$(document).on("click", ".btn-close", function(e){
$(e.currentTarget).parent().remove();
});
$('body').on('click','button id/class',function(){
$(e.currentTarget).parent().remove();
});
but if u use this code it will remove <div class="product-line">...</div>
why you want to remove this div.
i dont get your question very well. Explain in details and step by step .

Checkbox not unchecking visually

I have a form and within it is this:
<fieldset class="billing-address">
<legend>Billing Address</legend>
<ol>
<li class="text combi"><label for="bill-address1">Address:</label> <input size="20" value="" name="basket_order:default:bill_address1" id="bill-address1"></li>
<li class="text"><label for="bill-address2">Address:</label> <input size="20" value="" name="basket_order:default:bill_address2" id="bill-address2"></li>
<li class="text"><label for="bill-address3">Town/City:</label> <input size="20" value="" name="basket_order:default:bill_address3" id="bill-address3"></li>
<li class="text"><label for="bill-address4">Region:</label> <input size="20" value="" name="basket_order:default:bill_address4" id="bill-address4"></li>
<li class="text"><label for="bill-post-code">Post code:</label> <input size="10" value="" name="basket_order:default:bill_postcode" id="bill-post-code"></li>
</ol>
</fieldset>
For reasons too biring to go into here, I cannot get at the HTML directly and need to do things via javascript. So, I add a checkbox and label above using the following:
$('.billing-address ol').before('<input type="checkbox" id="billing-add-different" /><label for="billing-add-different">My billing address is the same as my delivery address</label>');
$('#billing-add-different').prop('checked',true).toggle(
function(){
$('.billing-address ol input, .billing-address ol select').css('background','#CCC').attr('disabled','disabled');
},
function(){
$('.billing-address ol input, .billing-address ol select').css('background','#FFF').removeAttr('disabled');
}
);
This toggles the 'disabled' attribute and background colour depending on whether it's ticked or not.
However, though the function is firing, the checkbox is still visually checked.
I've made a jsfiddle to illustrate at http://jsfiddle.net/EFQuh/. The error occurs in Firefox 8.0, not sure about others.
I don't know what is the problem (probably the toggle function), but you can simplify your code to:
$('#billing-add-different').prop('checked',true).change(function(){
$('.billing-address ol input, .billing-address ol select')
.css('background-color', this.checked ? '#CCC' : '#FFF')
.prop('disabled',this.checked);
}).change();
DEMO
You need to use the change event and check this.checked within the event's function.

Javascript: Edit a preview with jquery

I have 2 divs, the first one has the label with the content to show, but when you click the "edit" button, it should show you the div="edit" and the content of the 1st label inside of the input that is linked to it (same id).
By the other way, I saw sites that when you type something inside that input, the original label of the "preview" div is getting updated in realtime.
Could someone help me with the script? Thank you!
<html>
<body>
<div id="preview">
<label id="companyName" class="workExperience">
This is my company
</label>
<label id="companyCountry" class="workExperience">
This is my company Country
</label>
<input type="button" value="edit"/>
</div>
<div id="edit">
<label>Company Name: </label>
<input type="text" id="companyName" />
<label>Company Country: </label>
<input type="text" id="companyCountry" />
</div>
</body>
</html>
You can use something like below. Notice though that I changed the id of the fields to be different. It is not a good practice to give multiple controls on the same page the same id. Some browsers do not work with this and it really doesn't make sense anyways.
$(document).ready(
function()
{
$("#companyNameText").keypress(
function()
{
$("#companyNameLabel").html(this.value);
});
$("#companyCountryText").keypress(
function()
{
$("#companyCountryLabel").html(this.value);
});
});

Categories

Resources