jQuery not populating text field until page refreshed in Rails app - javascript

I've got a form that uses jQuery to set the value of a text field. The form doesn't work when the page is first loaded, but it does work after the refreshing the page To help, describe the problem, I recorded a ~30 second video (hosted on SwfCabin):
Any idea what might be causing this? I'm a jQuery newb and I've no clue!
Here's jQuery code
$(document).ready(function () {
$(".category").each(function () {
$(this).find("a").click(function (event) {
event.preventDefault();
var category = $(this).text();
$("#post_categories").val(category);
});
});
});
And here's the HTML form:
<form accept-charset="UTF-8" action="/posts" class="new_post" id="new_post"
method="post">
<div style="margin:0;padding:0;display:inline">
<input name="utf8" type="hidden" value="✓" />
<input name="authenticity_token" type="hidden" value="OCbmfFY1cNsaa5e+SbvcSrP0ubQTg432ECNGmvaU8bM="
/>
</div>
<p>
<label for="post_title">Title</label>
<input id="post_title" name="post[title]" type="text" />
</p>
<p>
<label for="post_url">Url</label>
<input id="post_url" name="post[url]" type="text" />
</p>
<p>
<label for="post_categories">Pick a category</label>
<input type="text" id="post_categories" />
</p>
<p>Available choices:</p>
<ul>
<li class="category"> programming
</li>
<li class="category"> cats
</li>
<li class="category"> batman
</li>
</ul>
<p>
<input name="commit" type="submit" value="Submit" />
</p>
</form>

Looks fine ,make sure you have included jQuery lib, also you can optimize the code a bit.
$(document).ready(function() {
$('.category a').click(function(event){
event.preventDefault();
var category = $(this).text();
$("#post_categories").val(category);
});
});
Fiddle: http://jsfiddle.net/DGW3Q/

I thought Arun P Johny and Farhan had provided the answer I was looking for, but it turns out I had a different problem. The app I'm writing is Ruby on Rails and I didn't get the memo about how Rails' Turbolinks overrides some jQuery functionality.
For example, by default in Rails 4.0.0, Turbolinks handles executing JavaScript on page load. This means I was trying to use $(document).ready(;, but Turbolinks had hijacked that functionality. For reasons I don't yet fully understand, refreshing re-enabled my jQuery script and then it started working. I guess Turbolinks' version of $(document).ready(; doesn't get reset when the page is refreshed?
As a short term hack, I ended up solving the problem by installing the RubyGem "jquery-turbolinks". At some point I'll need to learn how to use or disable Turbolinks. Maybe I should just learn to use Angular or Ember :) DOM shenanigans are a pain!
Ryan Bates discusses Turbolinks in Episode #290 of Railscases, including how code gets executed at page load.

Related

Tabs not switching, but stacking on top of each other. JavaScript

I have a small code in JS for 3 tabs in my page. They are meant to help me switch between those tabs without reloading the page. However, the tabs just show up one by one on top of each other and stay there. Could anyone please take a look and tell me what the problem is?
Also, if it's possible - after I've chosen a tab and tried to submit data from one of the tabs using a form and PHP and the validation did not pass, can I add something here so that the same tab stays active and is shown instead of the page just refreshing back to first tab? I would also like the same form stay there even if the form was submited successfully.
This is the JS part:
function onTabClick(event) {
let activeTabs = document.querySelectorAll('.active');
console.log(activeTabs);
// deactivate existing active tab and panel
for (let i = 0; i < activeTabs.length; i++) {
activeTabs[i].className = activeTabs[i].className.replace('active', '');
}
// activate new tab and panel
event.target.parentElement.className += 'active';
document.getElementById(event.target.href.split('#')[1]).className += 'active';
}
const elements = document.getElementsByClassName('nav-tab-element');
for (let i = 0; i < elements.length; i++) {
elements[i].addEventListener('click', onTabClick, false);
}
This is the HTML part. The tabs in UL element and one of the 3 forms. I didn't include all of them just so there isnt too much code here, but they got the right IDs.
<ul id="nav-tab" class="nav">
<li class="active">
<a class="nav-tab-element" href="#books">Books</a>
</li>
<li>
<a class="nav-tab-element" href="#dvds">DVD's</a>
</li>
<li>
<a class="nav-tab-element" href="#furniture">Furniture</a>
</li>
</ul>
<!-- Tabs -->
<form action="" method="POST">
<!-- Books Tab -->
<div class="tab-content active" id="books">
<div class="book-tab">
<input type="text" name="sku" placeholder="SKU" autocomplete="off">
</div>
<div class="book-tab">
<input type="text" name="name" placeholder="Name of the product" autocomplete="off">
</div>
<div class="book-tab">
<input type="text" name="price" placeholder="Product price" autocomplete="off">
</div>
<div class="book-tab">
<input type="text" name="size" placeholder="Weight in KG" autocomplete="off">
</div>
<!-- Submit Buttons -->
<div class="btn">
<input type="submit" value="Submit">
<input type="reset" value="Clear">
<input type="hidden" name="type" value="book">
</div>
</div>
</form>
And lastly, this is the CSS part:
.tab-content {
display: none;
}
.tab-content.active {
display: block;
}
Im very new to JS, therefore any help will be apreciated. Thank you.
Check your CSS. The CSS displays how the element looks and to some extent how it reacts to user input. JS will add to CSS to make the interactivity of the website
i would suggest using frameworks as they simplify A LOT of functionality. As such, you do not need to recreate the wheel.
my favorite right now is vuejs but i started with jQuery. Both these frameworks are based on javascript.
Another good framework is bootstrap which uses CSS and jQuery among a few others to streamline client side.
Check out tabs in bootstrap which handles all this functionality for you
If you want a tutorial using a similar approach of your check this out w3schools
Form posting
You can use AJAX to post the form to where ever and the form will look as though it was not posted. Therefore the tabs wouldnt need to be changed.
If you do not want to use ajax
Using your loop to attach the eventlister add check to see if the window url property is set. this article covers this

How do you change attributes in HTML that's generated by a script?

I'm using a widget script from a federated search service:
<script type="text/javascript" id="s9f5b2bb09b74013279b22ae8d1b2df50" src="http://uleth.summon.serialssolutions.com/widgets/box.js"></script>
<script type="text/javascript">new SummonCustomSearchBox({"id":"#s9f5b2bb09b74013279b22ae8d1b2df50","params":{},"colors":{},"searchbutton_text":"Search","suggest":"true","popup":"true"})</script>
Which generates the following HTML when the page loads:
<form id="s9f5b2bb09b74013279b22ae8d1b2df50" method="get" action="http://uleth.summon.serialssolutions.com/search" class="summon-search-widget" accept-charset="utf-8" target="_blank">
<input name="utf8" value="✓" type="hidden">
<div class="summon-search-box">
<input class="summon-search-field" name="s.q" autocomplete="off" placeholder="" data-boxwidth="" type="text">
<input value="Search" class="summon-search-submit button-website" type="submit">
</div>
</form>
I'm trying to use the following jquery to insert some placeholder test, but it' isn't working...
$(".summon-search-field").attr("placeholder", "Search for books, articles, videos...");
The jquery works on the generated HTML in this fiddle, but for some reason it can't get it to work on the page using the widget script. I can get it to work with a .click() function, but I can't get it to load with $(document).ready() or window.onload.
I apologize for not making a fiddle using the script as an external resource, but it doesn't work with https://.
How do I get my placeholder text to remain?
JSFiddle uses $(window).load(function(){
This waits for the entire page to load. If you experience further errors. Add:
$(window).load(function(){setTimeout(function () {
//Code
},1)});
$(window).load()

Redirecting after form submission in Javascript

I hope someone can assist with this. I dont have access to the website backend, so I cant change the js script uploaded there. What I am trying to achieve is make a simple form to submit an issue report and then display a "Thank you" popup and redirect back to main page of the account on our page.
So I can make a form no problem. I copied one of the functioning forms by going to Edit link and clicking on Show Source in Page Body. But I can't stop the default behavior of it going to another page after Submit button is pressed. I suspect it is in js script on the back end. I'll copy code below.
<center>
<b>App Issues Report Form</b>
<br>
</center>
<form action="/Modules/SendForm" method="post" class="form" id="NewForm">
<input name="formFields" value="CONTACTID,AgentName,Notes" type="hidden">
<input name="formLabels" value="Contact ID:,Agent Name:,Notes:" type="hidden">
<input name="fromAddress" value="no-reply#callcenter.com" type="hidden">
<input name="toAddress" value="name#CallCenter.com" type="hidden">
<input name="subject" value="A new message about app" type="hidden">
<input name="emailMsg" value="The following data has been collected:" type="hidden">
<input name="CONTACTID" value="##CONTACTID##" type="hidden">
<input name="companyId" value="##COMPANY_ID##" type="hidden">
<div class="clearfix">
<label>Agent Name:</label>
<div class="input"><input id="AgentName" name="AgentName"
class="validate[required] xlarge" value="##LOGGEDIN_AGENT_FIRST_NAME##
##LOGGEDIN_AGENT_LAST_NAME##" type="text">
</div>
</div>
<div class="clearfix">
<label>Notes:</label>
<div class="input"><textarea id="Notes" name="Notes"
class="validate[required] xxlarge"></textarea>
</div>
</div>
<div class="clearfix grey-highlight">
<div class="input no-label">
<input class="button blue" value="Submit" type="submit">
<input class="button grey" value="Reset" type="reset">
</div>
</div>
</form>
<script type="text/javascript">
$(document).ready(function() {
$("NewForm").click(function( event ) {
alert( "Thank you for your feedback" );
event.preventDefault();
});
});
</script>
It used to have only this at the end when I copied the code:
<script type="text/javascript">
$(document).ready(function () {
new setupAjaxForm('NewForm'); });
</script>
I tried searching and suggestions here didnt seem to work:
How to redirect user to another page after Ajax form submission
How to redirect user to another page after Ajax form submission?
http://learn.jquery.com/about-jquery/how-jquery-works/
The first thing you have to look at is action="/Modules/SendForm" - this is what does the redirection. If you don't want to redirect, set this to the name of the page you have the form. Obviously there is a whole lot more to forms and redirection (and some other js code might influence this too, nonetheless we don't see what the function setupAjaxForm is supposed to do here), but this is really the first thing to check / get right.
EDIT: I think I understand it more now: basically if you don't have access to the /Modules/SendForm page (where most probably, among others, like form validation, the redirection also happens, then you can't do much to change the redirection.

How do I post values obtained from an html form to an URL using javascript?

I'm new to html and JS and I have a form with a few fields that I need posted to a URL.
<form>
<div>
<label style="font-size:16px" for="title">Title:</label>
<input type="text" id="title" maxlength="128"/>
</div>
<div>
<label style="font-size:16px" for="description">Description:</label>
<textarea id="description" maxlength="1999"></textarea>
</div>
<div>
<label style="font-size:16px" for="idnumber">IDNumber:</label>
<input type="number" id="idnumber"/>
</div>
</form>
I need the values entered into this form to be posted to a URL that already knows how to process the input. I'm sure this is easy to do but I'm new and I'm having trouble finding a solution. Apologies for any incorrect terminology. Thanks!
You can use the action attribute:
<form action="some/url" method="post">
<!-- ... -->
<input type="submit" value="Submit" /> <!-- Submit button -->
</form>
You have to add an action to your form tag that points to a server side script.
<form action="myscript.php" method="post">
Alternatively, you can use JavaScript to post it as an AJAX request which submits the request without a page refresh.
I'd say you're on the right track. This would be perfectly easy using basic HTML: Add an action="mySubmitPage.php" to the form element. It sounds like you want to do it without refreshing/changing the page, though (at least, that's how it sounds by "with Javascript")
That will involve an "asynchronous" submit. The fancy term is "AJAX". That part can be a lot easier using some form of Javascript framework, especially if you want to support all browser quirks. Here's an example of doing it using JQuery, for instance:
jQuery - Send a form asynchronously

AOL 9.0 IE7 javascript Submit problem

I'm having some problems with AOL and IE 7.
Some members on my site have this setup and I'm having trouble getting some forms to work for them.
The html/javascript is this
<li >Award</li>
<form action="" name="form_user_award_give" method="post">
<input type="hidden" name="action" value="Give Award"/>
</form>
function photo_user_award_give() {
//simple function to submit a form
document.form_user_award_give.submit();
}
I've just taken the main bits just to give you a flavour.
I also have another problem with another button.
here is the code.
<li>
<form action="#edit_box" id="edit_photo_form" method="post">
<a onclick="document.getElementById('edit_photo_form').submit();" style="background-image:url('http://www.ephotozine.com/v5/images/site/pencil.png');" href="javascript:void(0)">Edit</a>
<input type="hidden" name="action" value="Edit"/>
</form>
</li>
I need to keep the elements as they for style are which is why I haven't used a submit button.
Does anyone have any ideas?
Or a place to download AOL 9.0?
Thanks
Richard
Got the answer instead of href="javascript:;" or href="javascipt:void;" use href="#" as the page is refreshing anyway this seems to do the trick. or event #nogo to keep the screen where it is

Categories

Resources