Focus specific 'id' after submit action - javascript

I want to focus on specific id (ex. using $('#a')) after submit.
There is nothing special with my code yet.
My javascript code is
function get_info(id){
$(user_id).submit();
$('#a).focus();
};
After submit, it should focus on where id='a'.
But after submit window focus on id='a' and reset the page.
I tried using
function get_info(id){
$(user_id).submit(function(e){
e.preventDefault();
$('#a').focus();
});
};
But this code make program worse. I think it stops performing submit.
Can anyone help me?

As Chris's comment says you couldn't focus on the element simply by using $('#a').focus(); after the submit since the page will be redirected/refreshed.
You need to use cookies or local storage, here a suggested sample using local storage like :
function get_info(id) {
localStorage.setItem('focusItem', '#a');
$(user_id).submit();
};
Then in the ready function, you could add :
$(function(){
var focusItem = localStorage.getItem('focusItem');
if( focusItem != null ){
$(focusItem).focus();
localStorage.removeItem('focusItem');
}
});

function SetFocus(){
$("#FocusingID").focus();}
/***********another way **********************//*
$("#submitbtnId").click(function(){
//your submession and other task;
$("#FocusingID2").focus();
});
*/
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type=text id=FocusingID>
<button type=submit onclick="SetFocus();">click</button>

Related

Auto POST Form on Interval is missing form field values

I have a script that works fine when a button is used to post the form. But when I convert the form to (auto)post on an interval, the form (field) values are missing when posted.
I know this has something to do with using the closest(form) as the button assists with closest (form) as a reference, but auto post on Interval has no reference for closest (form). Any help is appreciated thanks. By the way my form is on a sql while loop.
A) is the script when used with button.
B) is the script when used with a Auto(post) on interval.
The form)
<form class="updateform" action="" method="" >
<input type="hidden" class ="customerid" name="" value="<?php echo $customerid?>">
<a class ="test" >test</a>
<div class="update"> </div>
</form>
** A)**
<script>
$(document).ready(function(){
$('.test').click(function(event){
event.preventDefault();
var form = $(this).closest("form");
var field1= form.find('.customerid').val();
// Url to post to and Field name and content */
$.post('/test4.php', {customerid:field1},
// Alert Success
function(data){
// Alerts the results to this Div
form.find('.update').html(data);
});
});
});
</script>
** b)**
<script>
$(function() {
var form = $(this).closest("form");
var field1= $('.customerid').val();
function update() {
$.post("/test4.php", {customerid:field1},
function(data){
$('.update').html(data);
});
}
setInterval(update, 3000);
update();
});
</script>
It's probably because of the .closest() method in the second script. You are trying to select the form there which is closest to this up the tree. But in this case this will either be the scope of the function or the window object. Change it to a jQuery selector and select the correct form.
You can test this by yourself by either using console.log or the debugger statement to check what the values of the elements are in the developer tools of the browser. Get familiar with these guys, you'll need them a lot and are essential tools to even the most experienced developer.
If I may give a tip. Name your jQuery elements (the elements you select with $('element')) with a $ prefix. This way you know by reading the variable what kind of value that variable has. Also giving your variables meaningful names makes it even more easy to read and understand. field1 is generic, but customerIdField tells you what field it is.
$(function() {
var $form = $('form.updateform');
var $updateField = $form.find('.update')
var $customerIdField = form.find('.customerid');
var customerIdValue = $customerIdField.val();
function update() {
$.post("/test4.php", {customerid: customerIdValue}, function(data) {
$updateField.html(data);
});
}
setInterval(update, 3000);
update();
});

Clear the form/textarea after submit (emoji-picker with jquery)

In my form/textarea I use an emoji picker (https://github.com/mervick/emojionearea).
Idea is once user write some text/put some emoji and send this (“Submit”) the form will reset/clear.
My ongoing code: https://jsfiddle.net/byrvfwah/
Emoji picker works well, but I can’t clear the form after submit.
At the same time, without function which initiates an emoji-picker, the submit button clear the form: https://jsfiddle.net/9bps7f6v/3/
There are a lot of method to reset form and I already tried a lot of them:
$("#mytextarea").val('');
$('#mytextarea').trigger("reset");
$(‘#mytextarea').text('');
$("#mytextarea").reset();
$("#myform")[0].reset();
The explanations from the author of emoji-picker script not very useful:
https://github.com/mervick/emojionearea/issues/9
https://github.com/mervick/emojionearea/issues/54
https://github.com/mervick/emojionearea/issues/373
Any ideas how I can clear my form on submit?
You need to target emojionarea-editor class div and replace with empty '' string.
$(document).ready(function() {
$("#mytextarea").emojioneArea({
pickerPosition: "bottom"
});
});
$(document).ready(function() {
$("#mybutton").click(function(e) {
e.preventDefault();
$(".emojionearea-editor").html('');
});
});
It is not being cleaned because it is not a data input element rather it is a div. Inspecting the item you can see:
And has a class, so you can just clear the html:
$(document).ready(function() {
$("#mybutton").click(function(e) {
e.preventDefault();
$(".emojionearea-editor").html('');
});
});
$("#mytextarea").data("emojioneArea").setText('');

JavaScript and WordPress: button click not found by addEventListener

To prevent answers like: 'is the JavaScript file loaded?' -> Yes, it is loaded, at the footer part of the page! I have checked that with a simple message to the console, which is displayed!
But:
I've got a page with a button:
<button id="portfolio-posts-btn">Load portfolio related blog posts</button>
And a file main.js:
var portfolioPostsBtn = document.getElementById('portfolio-posts-btn');
var portfolioPostsContainer = document.getElementById("portfolio-posts-container");
if (portfolioPostsBtn) {
portfolioPostsBtn.addEventListener("click", function () {
console.log("the button was clicked!");
});
}
The text the button was clicked! should be displayed in the console, but it stays empty!
Apparently, the button click is not recognized, and thus, the var portfolioPostsBtn is false, or NULL... -> the method addEventListener() is not fired ?
I don't see the cause for this; I checked the spelling, should I use single or double quotes? Please help?
Thank you!
I've had this happen to me before, since theres two ways to do this I just used the other.
The first is onclick="function()", this is used as an attribute inside the element. Ex:
function clicked(){
alert("button clicked");
}
<button onclick="clicked();">Press me</button>
exaplaination: When you add this attribute to this element and I do believe some others when the button is clicked the specified code inside the quotes of the attibute will run. It doesn't have to be a number, e.g. onclick="alert(12+4/2);". But this is more of HTML than JavaScript using this version
The other way is using what you've got which (to me) is a lot more difficult then it needs to be. Heres my example
var b = document.getElementById("btn");
b.addEventListener("click", blogged);
function blogged(){
alert("this post has been blogged");
}
<button id="btn">Blog it</button>
This side of things has more to do with JavaScript and Event listeners. But the problem with you're code is that you're putting the event listener after you call the if statement. Here's my solution
var portfolioPostsBtn = document.getElementById('portfolio-posts-btn');
portfolioPostsBtn.addEventListener("click", function(){
check();
});
function check(){
if(portfolioPostsBtn){
console.log("posted");
}
}
<button id="portfolio-posts-btn">press this to post<button>
Presumably you have made a decision not to use jQuery. You'll need to wrap your code in an event listener so that the code is executed when the DOM is ready.
document.addEventListener("DOMContentLoaded", function(event) {
var portfolioPostsBtn = document.getElementById("portfolio-posts-btn");
var portfolioPostsContainer = document.getElementById("portfolio-posts-container");
if (portfolioPostsBtn) {
portfolioPostsBtn.addEventListener("click", function () {
console.log("the button was clicked!");
});
}
});
The answer is found in the uploading of the file page-portfolio.php!
I found out that the id="portfolio-posts-btn", added later, was not updated - could be my mistake, or the SFTP upload extension in Brackets - I did not see an error message!
Anyway, the issue is solved!
One more question: "are there methods to check if an id exists?". That could make live easier!
All contributors, thank you for your answers!

Div does not refresh when last character is deleted from input

I'm currently making a search function using a onkeyup="Search();" like this:
<input type="text" id="IDsearch" onkeyup="Search()" autofocus>
The function for it is:
<script type="text/javascript">
function Search() {
var inputVal = $('#IDsearch').val();
$.post('searchTest.php', {postname: inputVal},
function (data) {
$('#IDsearch').val(data)
});
$('#divRefresh').load('searchTest.php');
}
</script>
Yes, I am using the same file to both put the value in a php $_SESSION['value']; AND to store the new div data. That's no problem, it works, it does fine.
But when I delete my last character from my search box, I need to press backspace twice in order for my div to update.
Say I had a textbox with "a" in it. I will press backspace to update the a, and nothing will happen. Once I press backspace again, my div will update and post all the original values again.
Am I missing something obvious?
It's supposed to work the same way http://www.datatables.net/ does.
I have asked a question about this program before, but not about this issue, I hope it's not a problem.
I would go throught $("#IDsearch").keyup(function(){});
Tried your code with the function and didn't work, even with $("#divRefresh").html(theInputOfYours); The other way I mention to you works perfectly, even with backspace.
$(document).ready(function() {
$("#IDsearch").keyup(function() {
var value = $(this).val();
var posting = $.post("your_php_file.php", {val: value})
posting.done(function( data ) {
$( "#divRefresh" ).html(data);
});
});
});
The posting is a very basic example I can give, I use to go with $.ajax() function
Unfortunately, the behavior of keyup/keypress/keydown can be finicky sometimes, especially across different browsers.
A possible solution to ensure changes are tracked would be a listener that would track changes via a setInterval function that runs at an interval you specify.

How do you do a mandatory checkbox in a form?

I need a checkbox, where you move from one page to another after clicking the box. The checkbox should be required, given that you've read the terms and conditions link next to it.
I'm only half sure how to do this, something like this:
<input type="checkbox" value="confirm_prepay_terms" name="confirm_prepay_terms" align="middle" />
with Jquery:
<script type="text/javascript" language="javascript">
$(document).ready(function() {
if ($('form#prepay input:checkbox', 'confirm_prepay_terms').is(':checked') {
return true;
} else {
$('#confirm_terms_hint').text('Please try again - you need to check the box to move on');
$('#confirm_terms_hint').css('font-weight', 'strong');
return false;
}
}
</script>
At the moment though, I can't view the checkbox at all on the page, so perhaps my HTML is incorrect?
Hope you can help.
Your HTML is fine - is will show a checkbox - but without any text. You could add some using this markup :
<input type="checkbox" value="confirm_prepay_terms" name="confirm_prepay_terms" align="middle" >​Text here</input>​​​​​​​​​​​​​​​​​​​​​​​
In your JavaScript you are missing a closing ) :
if ($('form#prepay input:checkbox', 'confirm_prepay_terms').is(':checked') {
should be
if ($('form#prepay input:checkbox', 'confirm_prepay_terms').is(':checked')) {
and a ) on the last line :
}
</script>
should be
})
</script>
and your selector is incorrect
$('form#prepay input:checkbox', 'confirm_prepay_terms')
should be
$('form#prepay input:checkbox[name=confirm_prepay_terms]')
This uses the multiple attribute selector
and
$('#confirm_terms_hint').css('font-weight', 'strong');
should be
$('#confirm_terms_hint').css('font-weight', 'bold');
font-weight has no strong value (see here) ... use bold instead
in your script you are returning true or false but the code is not being called by anything - its executing as soon as the page has completed loading. Have a look at the .submit() method in jQuery if you want to perform form validation. An example would be this :
$(document).ready(function() {
$('#prepay').submit(function() {
if ($('form#prepay input:checkbox[name=confirm_prepay_terms]')) {
return true;
} else {
$('#confirm_terms_hint').text('Please try again - you need to check the box to move on');
$('#confirm_terms_hint').css('font-weight', 'bold');
return false;
}
});
});
This would prevent the form from being submitted now - as you return false to the submit event.
Fully working example here
I don't think it is necessary for you to provide a CheckBox as long as they must accept this terms and conditions before using the service.
You can just do the following and stress-less yourself .
- Provide a link to the terms and conditions for reading
- Notify them that they have automatically accept this terms while proceeding.

Categories