check if dynamically inserted input field exists - javascript

I have a script that adds a button that will open up a window that allows us to design t shirts. All i have top do is include their script and the button gets automatically added.
Below is the code which is dynamically added to the page.
<input id="design_edit_btn" class=" btn btn-success btn-block" value="Edit the design" type="button">
What i need to do is that, if that button is available then show a message saying its customizable or else display cannot be customized.
I tried the below code
if($("#design_edit_btn").length) {
alert("exists");
}
I did a bit of research but couldn't find a way to achieve this. Can someone please let me know how this can be done?
Thanks

You probably need to wait until the script has been loaded and executed.
Try waiting when the document is finished and do something like this:
jQuery(($) => {
if($("#design_edit_btn").length) {
alert("exists");
}
} );
jQuery triggers a given callback as soon as the document is ready. If that doesn't work either you could try adding a setTimeout as well.

Since the button you look for is create by an external script, that script is likely not finished by the time the DOM is ready, hence you won't find it, not even at $(document).ready()
What you can try is to use the script tag's onload, and when it fires, check for the button, like I do here, fire a console.log when jQuery have loaded.
Note, the order of the script is important
Stack snippet
<script>
function checkForjQuery() {
console.log('jQuery loaded');
}
function checkForButton() {
if ($("#design_edit_btn").length) {
alert("exists");
}
}
</script>
<script onload="checkForjQuery()" src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- temp. commented out
<script onload="checkForButton()" src="your_script_path"></script>
-->

have you tried something like this:
if(document.getElementById('design_edit_btn') != null)
{
alert("exists");
}

This should do the trick
if ($("#design_edit_btn").length > 0) {
alert("exists");
}

Related

Alternative to hide/show content with JS?

is there a better way to replace this kind of js function by simply collapse/toggle a div and show/hide its content?
$(function() {
$('#destselect').change(function(){
$('.dest').hide();
$('#' + $(this).val()).show();
});
});
The reason this is happening is because your js file is called on the head of your page.
Because of this, when you document.getElementsByClassName('collapsible');, colls result in an empty array, as your elements in body are not yet created.
You could either create a separate js file and add it at the end of your body (in that way you make sure your colls are created when your javascript is executed), or just wrap your code on a DOMContentLoaded event listener that will trigger your code once the document has completely loaded.
My guess would be that you are loading your script before browser finishes loading dom conetent and so when it runs the elements it is trying to add event listeners to, don't yet exist.
Try wrapping all you javascript in that file in this:
document.addEventListener("DOMContentLoaded", function(event) {
// all your code goes here
});
The above makes sure that your script is run after loading all elements on the page.
You could add a script tag to the header of your HTML file, this will import the JS file into your current page as follows
<script src="File1.js" type="text/javascript"></script>
Then call the function either in onclick in a button or in another script (usually at the bottom) of your page. Something like this:
<body>
...
<script type="text/javascript">
functionFromFile1()
</script>
</body>
Seems like your script is not executing properly due to a missing variable.
In this script https://www.argentina-fly.com/js/scripts.js
Naves variable in function UpdateDetailsDestination() is not defined.
I think you should resolve this first and then check your further code is working on not.
Please take a look into Console when running page. You'll see all JavaScript related errors there.

How to guarantee that a script in the middle of the body runs after all the DOM has finished load

In my <body> I have a component that inserts a script that is supposed to run only after all the page has completely loaded:
<script>
$('<script id="smallPlacarScriptdId">\
$(window).load(function() {\
$(".main.right").hide();\
$("#rightzero").show();\
$(".comp.smallPlacard.firstChild").click(function () {\
var clicked = $(this).parent().attr("id");\
$("main.right").hide();\
$("#right"+clicked+"").show();\
});\
})\
<\script>').appendTo("body")
</script>
That's not happening and this script (1) is correctly inserted into the DOM but (2) is not working (not hiding .main.right nor showing #rightzero).
I though that by using this approach I would guarantee that it would be the same as just put this script at the bottom of the <body> but it isn't. In fact if I put it (not dynamically like this) in my page it produces the desired result.
I tried setTimeout() to validate my theory but I'm getting an error in jQuery and I'm lost.
That might be the problem:
<\script>').appendTo("body")
Browser might think you are actually closing your script tag. Change it to
</' + 'script>').appendTo("body")
Check this plunker out: http://plnkr.co/edit/Oc6yrFMdPoW2WV257CBQ?p=preview
Just use this code
<script id="smallPlacarScriptdId">
$(window).load(function() {
$("main.right").hide();
$("#rightzero").show();
$(".comp.smallPlacard.firstChild").click(function () {
var clicked = $(this).parent().attr("id");
$("main.right").hide();
$("#right"+clicked+"").show();
});
})
</script>
Sorry I didn't read you question well enough.
Javascript will allow you to access undeclared variables, so use that to your advantage. Check if a variable is set, undefined is treated as a false so no need for initialization. As soon as you enter the code just set it to true so nothing else will execute.
Hopefully this solves the problem for you, but you really should look at from the server avoiding the javascript, it will bloat the page.
<script>
if (!myScriptHasLoaded)
{
myScriptHasLoaded = true;
$(window).load(function() {
$("main.right").hide();
$("#rightzero").show();
$(".comp.smallPlacard.firstChild").click(function () {
var clicked = $(this).parent().attr("id");
$("main.right").hide();
$("#right"+clicked+"").show();
});
});
}
</script>

Javascript/Jquery Boolean help: Hiding/Showing Divs

Can someone explain to me what i am doing wrong in this code?
http://jsfiddle.net/14njfqef/
var isLoggedIn = function(state){
if(state == true) {
$("#content-container").show();
$("#account2").show();
$("#account").hide();
}
else(state == false){
$("#content-container").hide();
$("#account2").hide();
$("#account").show();
}
}
onload=function() {
isLoggedIn(false);
}
On load i want the divs to hide but then when i click the button i want the divs to show?
Is the boolean function set out in the correct way?
Piece below tries to re-arrange piece at OP. onload not appear clearly defined , not addressed , though could be attached to an event , i.e.g., window.onload = onload . Wrapped blocks in jquery .ready() event . Removed js onclick markup from html , included at script element , or loaded from file at jquery .on("click") event . Added strict comparison operator === (an added =) to if / else if statements. Changed input type to button. Added if to else portion of composition (see link posted at comments by Felix Kling).
Try
$(function() {
var isLoggedIn = function(state){
if(state === true) {
$("#content-container").show();
$("#account2").show();
$("#account").hide();
}
else if(state === false){
$("#content-container").hide();
$("#account2").hide();
$("#account").show();
}
};
isLoggedIn(false);
$("input[type=button]").click(function() {
isLoggedIn(true)
})
});
jsfiddle http://jsfiddle.net/guest271314/14njfqef/3/
changed your html to
<input type="submit" value="Boolean" id="toggle"/>
rewrote your js as
// JQuery run at start effectivly
$(document).ready(function() {
function isLoggedIn(state) {
if(state == true) {
$("#content-container").show();
$("#account2").show();
$("#account").hide();
}
else {
$("#content-container").hide();
$("#account2").hide();
$("#account").show();
}
}
// JQuery attaching a click event using an anonymous function
// and hard coding your isLoggedIn to true, passing variables is a bit more complicated.
$('#toggle').click(function() {isLoggedIn(true)});
isLoggedIn(false);
})
Well there's a few things I am not sure if you are aware of so I feel there's some responsibility on my end to make sure they are mentioned. They are a number of syntactical errors in your post that are stopping this from working so instead of addressing them I feel its necessary to update your view on what JQuery you are using as well as your selector choice.
First I would add a class structure to all of the div's to target them all at once so you can save on some lines of code. In production it's always better to have less code for all of your visitors to download because even a little bit of code can get out of control after enough hits on a webpage. Having to serve it kills speed and so does having to process three separate jquery selections as opposed to one.
I would change the HTML to...
<body>
<div id='content-container' class='boxes'>
Content Container
</div>
<div id='account' class='boxes'>
account
</div>
<div id='account2' class='boxes'>
account2
</div>
<input id="validateButton" type="submit" value="Boolean">
</body>
This way you can simply target all divs with $(".boxes"); ... I wouldn't recommend getting into the habbit of using $("div");
Next I would change the JQuery to being more JQuery friendly code. Its not always useful to use an onload event from pure Javascript to handle JQuery driven functions in correct time to the loading of DOM objects. Therefore you should use $( document ).ready( handler ) to handle this load event properly just in case it causes you problems down the road. The more common shorthand of this ready event is a simple $(function() { }); wrapper.
The rest of the code can be re-arranged to this....
var isLoggedIn = false; //<--Instantiate to false, make global to window level scope
//Load event Corrected For JQuery
$(function() {
$(".boxes").hide(); //<--Hide on load
//Add A Proper Updated Click Event To Button
$("#validateButton").click(function() {
isLoggedIn = true; //<--Should include real functionality not hand coded to true
checkLoginAndRespond(); //<--Validate Login Status
});
});
function checkLoginAndRespond() {
//If Logged, Show
if(isLoggedIn) {
$(".boxes").show();
//Else Don't
} else { $(".boxes").hide(); }
} //end function
Lastly, the version. New versions of JQuery have not been released for some time and seem to not be in the making so its a safe bet to use their most recent versions as it has thousands of pages of help for its syntax and it's very stable. I would recommend anything in the 2.0 or higher series JQuery.
I am assuming you have JQuery library loaded. Try
if (state) {
$("#content-container").show();
$("#account2").show();
$("#account").hide();
}
else{
$("#content-container").hide();
$("#account2").hide();
$("#account").show();
}
to solve your problem.

How to reference html element from included js-file

I created this test case which works as expected:
<script src="https://code.jquery.com/jquery-1.10.2.min.js"></script>
<script src="site.js"></script>
<script>
function click_me() {
deActivateButton("Please wait ..", "#btnX");
activateButton("Click me 2", "#btnX");
}
</script>
<button type="button" id="btnX" onclick="click_me(); return false;">Click me
</button>
And then two small functions kept in site.js to deactivate/activate my buttons:
function deActivateButton(btnText, id) {
$(id).text(btnText);
$(id).prop("disabled", true);
}
function activateButton(btnText, id) {
$(id).text(btnText);
$(id).prop("disabled", false);
}
This works fine, but fails when I use the code in my application. I'm using web forms with a master page. The master page loads include file:
<%Response.WriteFile("Content/Files/master_include_head.html");%>
And then in master_include_head.html I include the actual javascript functions like this:
<script src="site.js"></script>
What can I be doing wrong here? There are no error messages, it just dies. Shouldn't I be able to reference the id of the clicked button with this design, or is the reference to the button lost because of the way I include files? Can it be a cache problem?
Are you not just setting and then clearing then immediately clearing the value in your code?
So you are activating then immediately de-activating your button?
Just a little note. Why not use jQuery to attach your click events as follows:
$("#btnX").click(function(e) {
// Do stuff
});
Side note. I'm not sure there's any need for the return false; statement in your onclick. Typically this would just contain the function name. return false; can be used in functions to prevent event bubbling, as you've set it I'm not sure it will have any effec

simple jQuery function working in codepen but not on server:

So I have this little function that takes the value or text input and gives it to an iframe's src attribute. It seems to work great on my codepen, but when I export it (with all of the files etc(codepen style) (jquery and everything is loaded properly) and put it on a server, it doesn't work. Does anyone have any ideas why this might be? or how I could be going about this in a better way? --
this is what shows in the url bar on submit with the live version in chrome if that means anything to you.
http://site.com/?url-input=http%3A%2F%2Fmy-site.com
A working codepen
HTML
<form class="visitor-input-form">
<label for="url-input" >
Type in your current URL and see what your website looks like to almost everyone else.
</label>
<input type="text" name="url-input"
class="currentUrl"
placeholder="http://nouveau.io" id="txtSRC" />
<input type="submit" class="submit-button" value="View site" />
</form>
jQuery
$(".submit-button").click( function() {
$(".i-frame").attr("src", $("#txtSRC").val());
});
Thanks for your time.
Update:
So to further test I'm using this. Page loads, tells me the dom is ready. So everything is loading in order. Then I input the url, it tells me the button was pushed, THEN - it tells me the dom is ready AGAIN. So, when I'm pressing enter, it is reloading the page. I do not want the page to reload. I just want the iframe to get switched out. So that is at least a little window to what might be the problem.
jQuery( document ).ready(function($) {
alert("dom is ready");
$(".submit-button").click( function() {
alert("button was pushed");
$(".i-frame").attr("src", $("#txtSRC").val());
});
}); // end dom ready
Make sure you either execute your jQuery at the end of the document, after the elements already exist in the page, or in the head within a document ready call:
$(document).ready(function () {
$(".submit-button").click(function () {
$(".i-frame").attr("src", $("#txtSRC").val());
});
});
Codepen does the former.
We found this:
Prevent reloading page after submiting form. ( no ajax )
<form onsubmit="return false">
Does the trick, but I have the feeling there is a better answer. I feel like on submit, it should run the scrip maybe instead of on click. I'm going to look into that. <form onsubmit="script"> etc... I'll wait a while before I mark this as answered in the hopes I get something more appropriate, but it is currently working as intended.
The page is reloading, try updating your jQuery to this:
jQuery( document ).ready(function($) {
$(".submit-button").click( function(e) {
e.preventDefault();
$(".i-frame").attr("src", $("#txtSRC").val());
});
});

Categories

Resources