currently I'm trying to make it so that when the user clicks a link it submits the corresponding form via javascript. I used document.getElementById("id").submit() as a basis on how to send the form so my code should act similar to it in my understanding.
Here's the code:
function run(clickedLink){
clickedLink.id.submit(); //I did it like this since document.getElementById just gets the form id and since link and form have similar id's I thought it would send
}
<form id = 'formId'>
<a href = '#' id = 'formId' onclick = run(this)>Link</a>
</form>
I tried going with name = 'formId' too but it still doesn't run as I wanted it too.
Note: doing this since this code iterates dynamically and the id gets updated i.e. formID1, formID2...
Better ways to implement this are welcome too
Modify your function as follows
function run(clickedLink){
clickedLink.parentNode.submit(); // parentNode refers to the form element
}
You cannot use same id on the same page for more than one element. This is against HTML and DOM specifications https://softwareengineering.stackexchange.com/questions/127178/two-html-elements-with-same-id-attribute-how-bad-is-it-really .
You can change it to class if you want to reuse or you can change the id itself of other element. Also links are not recommended to submit the form. Their job is to navigate
Try this:
<a href="#" onclick="document.forms[0].v.value='Link1';
document.forms[0].submit();">Link 1</a>
One Basic thing:
-ID's are used to Uniquely Describe The Element in DOM Hierarchy. Please Don't Repeat it. (it is really bad)
Now to the answer:
function run(x){
var y=findParentForm(x); /* if Id's aren't Unique */
// If iD's are Unique :- var y=document.getElementById("formId");
y.submit();
}
function findParentForm(elem){
/*
This function will find exact parent form
even if link or elem is inside <div> or other complex DOM structure
This will Only return the parent <form> of that elemnt
*/
var parent = elem.parentNode;
if(parent && parent.tagName != 'FORM'){
parent = findParentForm(parent);
}
return parent;
}
<form id='formId' action="Server Side Script" method="GET/POST">
Link <!-- change id of link -->
</form>
Related
Is it possible to assign HTML text within an element to a JavaScript variable? After much Googling, I note that you can assign HTML elements to a variable, but I want the actual text itself.
Details about my goal:
I am currently working on a CRUD application, and with the click of a delete button, a modal will display and ask the user for confirmation before deleting the record. Once the button has been clicked, I want to retrieve HTML text within a specific element used for AJAX call data. However, what I have tried so far is not being logged to the console; even when I change the global variable to var deleteLocationID = "test"; I doubt the modal displaying will affect the click function?
The code:
var deleteLocationID;
$("#deleteLocationBtn").click(function () {
deleteLocationID = $(document).find(".locationID").val();
console.log(deleteLocationID);
});
What I have tried so far:
Changing "deleteLocationID = $(document).find(".locationID").val();" to the following variations:
deleteLocationID = $(document).find(".locationID").html();
deleteLocationID = $(".locationID").val() / deleteLocationID = $(".locationID").html();
deleteLocationID = document.getElementsByClassName("locationID").value;
Any help would be much appreciated.
Use the text() method from JQuery, with this you can get the text inside of your element.
Use this way, it may help you:
deleteLocationID = $(document).find(".locationID").text()
Here is example of getting text from class element:
$('.locationID').text()
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<div class="locationID">45</div>
It depends on the type of element you are trying to find your value.
for input types you can find the value by .val() in jQuery like:
$(document).find(".locationID").val();
you can grab innerHTML of the element by .html() in jQuery like:
$(".locationID").html();
but if you want to grab innerText of an element you can use .text() in jQuery like:
$(".locationID").text();
I'm mapping currencies from a json file and i render the mapped currencies to a component. I have a .php file like this
<div class="currency-switch-container" id="currency_container">
<span style="font-size:12px;font-weight:bold">All currencies</span>
<div id="currency-map" style="margin-top:15px"></div>
</div>
I refer the div in the above component in my js file as follows
let currencyMap = jQuery("#currency-map");
And when my jQuery document is ready i'm doing the following
jQuery(document).ready(function($) {
$.getJSON('wp-content/themes/mundana/currency/currency.json', function(data) {
for(let c in data){
currencyMap.append(`<span onclick="onCurrencyClick(${data[c].abbreviation})"
class="currency-item">
<span>
${data[c].symbol}
</span>
<span>
${data[c].currency}
</span>
</span>`)
}
});
}
and my function is like this
function onCurrencyClick(val){
console.log("val",val);
setCookie("booking_currency", val, 14);
}
Here the function does not work. But if i do not pass anything to the function it seems to work as i can see the log in the terminal.
Hi your expression ${data[c].abbreviation} will put the value into function string without string quotes i.e. the resultant would be onCurrencyClick(abbreviation) while it should be onCurrencyClick('abbreviation').
please use onclick="onCurrencyClick('${data[c].abbreviation}')" instead.
Instead of using the inline onclick, use event delegation. This means that you have a single event listener that handles all the events from the children and grandchildren. The modification is a very minor one seeing the example here below.
A reason for doing this is that you keep your JavaScript inside your JS file. Like now, you encounter a JS error and have to look for it in your HTML. That can get very confusing. Also however inline onclick listeners are valid, they are outdated and should be avoided unless there is absolutely no other way. Compare it with using !important in CSS, same goes for that.
function onCurrencyClick(event){
var val = $(this).val();
setCookie("booking_currency", val, 14);
}
currencyMap.on('click', '.currency-item', onCurrencyClick);
This example takes the val that you try to insert from the value attribute from the clicked .current-item. <span> elements don't have such an attribute, but a <button> does and is a much more suitable element for it expects to be interacted with. It is generally a good practice to use clickable elements for purposes such as clicking.
In the example below you see the button being used and the abbreviation value being output in the value attribute of the <button> element and can be read from the onCurrencyClick function.
jQuery(document).ready(function($) {
$.getJSON('wp-content/themes/mundana/currency/currency.json', function(data) {
for(let c in data){
currencyMap.append(`
<button value="${data[c].abbreviation}" class="currency-item">
<span>
${data[c].symbol}
</span>
<span>
${data[c].currency}
</span>
</button>
`)
}
});
onclick will not work for a dynamically added div tag
Yo should follow jQuery on event
Refer: jQuery on
Stackoverflow Refer: Dynamic HTML Elements
Ok, I will try explain my question.
I need to add class ".active" into already existing class ".jobs", when URL have hashtag same as ID, inside tag with class ".jobs".
Here is working code just for one compare:
$(document).ready(function() {
var hashVal = window.location.hash.split("#")[1];
if(hashVal == 'programmer') {
$("#programmer").addClass('active');
}
});
In practice:
Someone will come to website www.domain.tld/jobs#programmer then I need compare "#programmer" from ULR with all existing IDs in all <div> tags, which also have class ".jobs", and if there will be someone with class="jobs" and also id="programmer", I need to add into this <div> tag class "active".
Is there a way to make jQuery code more variable? Like without having add comparison for each ID name? and also I need to move browser windows on position, where div with that ID it is.
var hashVal = window.location.hash.split("#")[1];
if($('#'+hashVal).hasClass('jobs')) $('#'+hashVal).addClass('active');
this is the div im trying to copy
{%for i in current_user.posts%}
<div class = "own_posts" id = "{{'id_' + i.id|string}}">
<img src = "{{url_for('static',filename='user_prof_pic/' + current_user.prof_pic)}}">
{{current_user.first_name}}
<p>{{i.post}}</p>
<div class ="like_comment">
<ul>
<li>like</li>
<li>comment</li>
</ul>
</div>
<form class ="comment_form">
<input type="text" action = "#" name = "comment_box" class ="comment_box" id = "{{'id_' +i.id|string}}">
<input type="submit" value="comment" class ="submit" id = "{{'id_' + i.id|string}}">
</form>
</div>
{%endfor%}
so far I've been successful at prepending it and changing the newly prepended div's ID using jquery like this.
var count = 4
$(".submit").click(function(event){
event.preventDefault()
var id = $(this).attr("id")
var comment = $(".comment_box#" + id).val()
console.log(count)
count++
$.ajax({
type:"POST",
url:"#",//"{{url_for('main.ProfilePage',user = current_user.first_name)}}",
data: JSON.stringify({"comments":comment}),
contentType:"application/json;charset=UTF-8"
});
var div_copy = $(".own_posts#id_2").clone()
var div_copy2 = div_copy.attr("id","id_" + count)
$("#own_stream").prepend(div_copy2)
});
however the form ID within the prepended div still contains the ID of the div it was cloned from. to clarify
var div_copy = $(".own_posts#id_2").clone() the form in this div contains an id of id_2 so the newly prepended div's form id is still id_2
I changed the prepended div's ID doing this:
var div_copy = $(".own_posts#id_2").clone()
var div_copy2 = div_copy.attr("id","id_" + count)
$("#own_stream").prepend(div_copy2)
but I don't know how to access the form within this newly cloned div and change it's form ID.
how do we achieve this?
also am I doing this right? Im trying to learn web development and wan't to understand how sites like facebook,twitter etc. are showing your newly posted statuses/tweets into the page without refreshing it.
is what I'm doing the gist of how that works? if not
shed some light on a newbie
also this is just a test to practice the concepts
If all you are attempting to do is retrieve the form element using jQuery, based on your source, you have multiple options.
var form = $(".own_posts#id_2 > form");
/* or */
var form = $(".own_posts#id_2 > .comment_form");
I don't normally suggest the direct descendant method because if your genealogy changes in the future, it will fail. You are using templates so intuitively I see future changes to it a possibility. Using a unique identifier or known singular class and searching the entire div chain makes more sense to me.
var form = $(".own_posts#id_2 .comment_form");
/* or */
var form = $(".own_posts#id_2").find(".comment_form");
Those two options should be roughly equivalent for your purpose and can use either.
Also I would be careful with non-unique ids. You may get away with it by only searching smaller scoping chains, but you're only supposed to have one on the page. This is why most functions that retrieve by id will return only the first object found, rather than a collection.
I don't know how you're using the ids, but perhaps something like id="{{'posts_' + i.id|string}}" and so on to utilize unique prefixes.
I am working on a script that is meant to pull the inner html of a paragraph that is only shown onblur. I have spent hours on this and have not been able to successfully surface this inner html in our data layer.
Firstly, the data layer is custom (i.e. not the default data layer for GTM) - not sure if this makes a difference.
Secondly, the JavaScript I am using to attempt to achieve this. The onblur listener shows a parahraph (with no Element ID, only Element Class) when a user moves on from the form (which is the first parent element which has an ID, it is several parent elements up from the class). The paragraph passes a validation message (e.g. enter a valid email). I am attempting to pass the error message to the data layer:
<script>
object.onblur=function(){
var myForm = document.getElementById('instantSearchForm');
if(myForm) {
var myPara = myForm.getElementsByTagName('error-message');
if(myPara.length) {
var paraValue = myPara[0].innerHTML;
dataLayer.push({inputError: paraValue });
}
}}
</script>
As per your comment I see that you are using the class name for selecting your elements. Then you should try
myForm.getElementsByClassName('error-message');
instead of
myForm.getElementsByTagName('error-message');