Cannot Click button on webpage - javascript

Is there any reason why the prompt will not appear when clicking the bottom on my web page? The other buttons works on my web page fine but the "create room" button will not work and I am not sure why.
Any Ideas?
ViewBag.Title = "Chat";
}
<h2>General Chat</h2>
<div id="wrapper">
<div id="upper-wrapper">
<div id="available-rooms-dialog">
<h4>Available Rooms</h4>
<input type="button" onclick="s = prompt('Enter a new Room Name', 'Name');" id=" createroom" value="Create Room" />
</div>
<div id="discussion-dialog">
<textarea rows="30" cols="50" id="discussion"></textarea>
</div>
</div>
<div id="message-dialog">
<textarea rows="3" id="message">Type your message</textarea>
<br/>
<input type="button" id="sendmessage" value="Post" />
<input type="hidden" id="displayname" />
<input type="checkbox" id="enter-sends-message"/>
Enter sends message
</div>
</div>
#section scripts {
<!--Script references. -->
<!--The jQuery library is required and is referenced by default in _Layout.cshtml. -->
<!--Reference the SignalR library. -->
<script src="~/Scripts/jquery.signalR-2.0.2.min.js"></script>
<!--Reference the autogenerated SignalR hub script. -->
<script src="~/signalr/hubs"></script>
<!--SignalR script to update the chat page and send messages.-->
<script type="text/javascript">
var json;
$(function () {
// Reference the auto-generated proxy for the hub.
var chat = $.connection.chatHub;
// Create a function that the hub can call back to display messages.
chat.client.addNewMessageToPage = function (name, message) {
// Add the message to the page.
//TODO: Add Record to Server
$.ajax(
{
type: "Post",
url: "#Url.Action("AddMessage", "Home")",
data: { messageCont: message.toString() },
success: function (data) {
for (var i = 0; i < data.length; i++) {
//access with data[i].modelattribute
}
}
});
$.ajax(
{
type: "Get",
url: "#Url.Action("GetMessages", "Home")",
success: function (data) {
json = data;
var obj = JSON.parse(json);
for (var i = 0; i < data.length; i++) {
//access with data[i].modelattribute
$('#discussion').append(htmlEncode(obj[i].Author) + " : " + htmlEncode(obj[i].Message) + "\r\n");
}
}
});
};
// Get the user name and store it to prepend to messages.
$('#displayname').val(prompt('Enter your name:', ''));
// Set initial focus to message input box.
$('#message').focus();
// Start the connection.
$.connection.hub.start().done(function () {
$('#sendmessage').click(function () {
// Call the Send method on the hub.
chat.server.send($('#displayname').val(), $('#message').val());
// Clear text box and reset focus for next comment.
$('#message').val('').focus();
});
});
});
// This optional function html-encodes messages for display in the page.
function htmlEncode(value) {
var encodedValue = $('<div />').text(value).html();
return encodedValue;
}
</script>
}

Related

textarea not send form do not send form the first click to send. The at 2 click yes

In a Tinymce textarea, it forces me to double click submit form. In the first send "var a" is empty, in the second click if you have the data and it is sent correctly. How can it be solved?
<script src="https://cdn.tiny.cloud/1/zgxpx6ymtwpuc7yy5x3wuic7eu7ughi6w7q98msfnxmbcpjp/tinymce/5/tinymce.min.js" referrerpolicy="origin"></script>
<script>
tinymce.init({
selector: '#comment',
});
</script>
<script type="text/javascript">
function FQB() {
var a = document.forms["Formularioqr"]["comment"].value;
if (a == null || a == "") {
alert(a);
return false;
}else{
a = a.replace(/\r?\n/g, '<br />');
$.ajax({
type: "POST",
url: "send-email-manual-envio.php?mesaje=" + a + "&correo=<?php echo $correo;?>" ,
dataType: "json",
success: function() {
document.getElementById("Formularioqr").reset();
document.getElementById("showtextqr1").innerHTML =" Enviado Con exito ";
},
error: function() {
document.getElementById("Formularioqr").reset();
document.getElementById("showtextqr1").innerHTML = " ERROR!!";
}
});
}
}
</script>
<form method="POST" autocomplete="off" id="Formularioqr" name="Formularioqr" onsubmit="return FQB()">
<div class="form-group">
<label for="comment">Mesaje:</label>
<textarea class="form-control" rows="12" id="comment" name="comment"></textarea>
</div>
<p id="showtextqr1"></p>
<input type="submit" value="Enviar">
</form>
I haven't tried it, but i would guess, that '.value' isn't working properly for tinymce textareas.. the tinymce has an dedicated function to get the content. See https://www.tiny.cloud/blog/how-to-get-content-and-set-content-in-tinymce/
I would suggest, trying this way instead this var a = document.forms["Formularioqr"]["comment"].value;

google invisible recaptcha keeps running without execute

I'm trying to use google invisible recaptcha on my web form (php and codeigniter 3). but somehow whenever I click on the Submit button, the google recaptcha keeps generating questions as if ignoring all the other codes before the execute command. so none of the console.log and alert ever appear. what is wrong with my code?
my code looks like this:
HTML
<form id="form_signup" method="post" action="/signup">
<input type="text" name="username"/>
<div class="g-recaptcha"
id="form_signup-recaptcha"
data-size="invisible"
data-sitekey="<?php echo $mysitekey; ?>"
data-callback="onSubmitFormSignupUser">
</div>
<button type="button" id="formSignup-btnSubmit">
Submit
</button>
</form>
JS
var widgetId = '';
var onLoadRecaptcha = function() {
widgetId = grecaptcha.render('formSignup-btnSubmit', {
'sitekey' : $('#form_signup-recaptcha').attr('data-sitekey'),
'callback' : $('#form_signup-recaptcha').attr('data-callback'),
});
};
var onSubmitFormSignupUser = function(response) {
console.log('response', response);
if ($('[name="username"]').val()) {
alert('yes');
grecaptcha.execute(widgetId);
doSubmitFormToServer('#form_signup');
}
else {
alert('no');
grecaptcha.reset(widgetId);
}
}
var doSubmitFormToServer = function(selector) {
var myData = $(selector).serializeArray();
console.log('send form data', myData);
}
Well, you had a typo in the id, at least, here id="form_signup-recaptcha" and here: 'sitekey' : $('#formSignup-recaptcha').attr('data-sitekey'),, other than that, it is not clear, was it invoked at all, or not, as you've not provided the part of including the script, which should contain ?onload=onLoadRecaptcha parameter.
The code is below, but it won't work here, because of null origin. Check Codepen instead: https://codepen.io/extempl/pen/abOvBZv
sitekey used is one is for testing purposes only, as described here: https://developers.google.com/recaptcha/docs/faq#id-like-to-run-automated-tests-with-recaptcha-v2-what-should-i-do
var widgetId = "";
var onLoadRecaptcha = function() {
widgetId = grecaptcha.render("formSignup-btnSubmit", {
sitekey: $("#form_signup-recaptcha").attr("data-sitekey"),
callback: $("#form_signup-recaptcha").attr("data-callback")
});
};
var onSubmitFormSignupUser = function(response) {
console.log("response", response);
if ($('[name="username"]').val()) {
grecaptcha.execute(widgetId);
doSubmitFormToServer("#form_signup");
} else {
$(".status").text("failed");
grecaptcha.reset(widgetId);
}
};
var doSubmitFormToServer = function(selector) {
var myData = $(selector).serializeArray();
$(".status").text("submitted");
console.log("send form data", myData);
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://www.google.com/recaptcha/api.js?onload=onLoadRecaptcha"></script>
<body>
<form id="form_signup" method="post" action="/signup">
<input type="text" name="username" />
<div
class="g-recaptcha"
id="form_signup-recaptcha"
data-size="invisible"
data-sitekey="6LeIxAcTAAAAAJcZVRqyHh71UMIEGNQ_MXjiZKhI"
data-callback="onSubmitFormSignupUser">
</div>
<button type="button" id="formSignup-btnSubmit">
Submit
</button>
<span class="status"></span>
</form>
</body>
it turns out that the solution is so simple.
this code
var onLoadRecaptcha = function() {
widgetId = grecaptcha.render("formSignup-btnSubmit", { // wrong element ID
sitekey: $("#form_signup-recaptcha").attr("data-sitekey"),
callback: $("#form_signup-recaptcha").attr("data-callback")
});
};
should be like this
var onLoadRecaptcha = function() {
widgetId = grecaptcha.render("form_signup-recaptcha", { // corrent element ID
sitekey: $("#form_signup-recaptcha").attr("data-sitekey"),
callback: $("#form_signup-recaptcha").attr("data-callback")
});
};
because the recaptcha element is like this
<div
class="g-recaptcha"
id="form_signup-recaptcha"
data-size="invisible"
data-sitekey="6LeIxAcTAAAAAJcZVRqyHh71UMIEGNQ_MXjiZKhI"
data-callback="onSubmitFormSignupUser">
</div>
so basically the parameters for grecaptcha.render should follow the properties in the element that has g-recaptcha class. my mistake was that I used the button id, even though the element with g-recaptcha class was the div.
I don't remember reading about this particular thing in the documentation. I guess I'm too stupid to realize that before this.. I hope this makes things clear for others with the same problem.

Materialize - AutoComplete hiding when changing data with ajax

I'm making a form using MaterializeCSS and jQuery. I got 2 fields : Name and ID.
The field Name is an AutoComplete field that gets the right data. The ID field is not important.
I'm trying to implement a functionality to get data as the user writes.
The problem occurs when the user writes : the data "behind" the AutoComplete is changing properly, but the dropdown component of the AutoComplete hides. The user must click outside of the AutoComplete field and click back on it to see the changes, which is absolutely not user-friendly.
$(document).ready(function () {
//Autocomplete
$(function () {
$.ajax({
type: 'GET',
url: 'https://reqres.in/api/users?page=1',
success: function (response) {
var nameArray = response.data;
var dataName = {};
console.log('nameArray = ' + JSON.stringify(nameArray, 4, 4));
for (var i = 0; i < nameArray.length; i++) {
dataName[nameArray[i].last_name] = nameArray[i].flag;
}
console.log('dataName = ' + JSON.stringify(dataName, 4, 4));
$('#name_autocomplete').autocomplete({
data: dataName,
limit: 5, // The max amount of results that can be shown at once. Default: Infinity.
});
}
});
});
});
$(document).ready(function () {
$('#name_autocomplete').keyup(function () {
$(function () {
$.ajax({
type: 'GET',
url: 'https://reqres.in/api/users?page=2',
success: function (response) {
var nameArray = response.data;
var dataName = {};
console.log('nameArray = ' + JSON.stringify(nameArray, 4, 4));
for (var i = 0; i < nameArray.length; i++) {
dataName[nameArray[i].last_name] = nameArray[i].flag;
}
console.log('dataName = ' + JSON.stringify(dataName, 4, 4));
$('#name_autocomplete').autocomplete({
data: dataName,
limit: 5, // The max amount of results that can be shown at once. Default: Infinity.
});
}
});
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0-beta/js/materialize.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0-beta/css/materialize.min.css" rel="stylesheet"/>
<main>
<div class="container">
<div id="main_panel_form" class="card-panel col s12">
<div class="row">
<form class="col s12" action="/test">
<div class="row">
<div class="input-field col s4">
<input id="name_autocomplete" name="name_autocomplete" type="text" class="autocomplete">
<label id='label_name_autocomplete' for="name_autocomplete" class="active">Name</label>
</div>
<div class="input-field col s3">
<input id="id" name="id" type="text" class="autocomplete">
<label id="label_id" for="id">ID</label>
</div>
</div>
<div class="row center-align">
<button class="btn waves-effect waves-light" type="submit" value="Submit">Submit</button>
</div>
</form>
</div>
</div>
</div>
</main>
On this example, when the user starts to write, it gets new data (from ?page=1 to ?page=2)
I'd like to see the data of the AutoComplete change while it remains opened.
I've also made an example on Codepen
The AutoComplete component hides each time the user writes because you initialize #name_autocomplete for each keyup. Each time the init function is called, it closes the autocomplete suggestions.
Materialize has a specific method updateData to refresh the initial object provided: http://materializecss.com/autocomplete.html
I took your codePen and refactored it so you can have an example of the autocomplete method updateData. Codepen

Debugging failing jQuery validate addMethod

I have a page where almost every click is handled by delegate().
http://itsneworleans.com/shows/midnight-menu-plus-1/blogs/after-midnight?preview=1
I set up jQuery validate like so
$(document).ready(function(){
$(".commentform form").validate({
rules: {
antispam: { equalToParam: "INO" }
}
});
jQuery.validator.addMethod("equalToParam", function(value, element, param) {
return value == param;
},
"Anti-spam field does not match requested value.");
});
if I check in console with
$.validator.methods['equalToParam']
I get back
function (value, element, param) { return value == param; }
so that looks good.
The validation works on the form submission BUT the equalToParam method has no effect. Only the "required" events occur for it.
The field HTML is
<input name="antispam" type="text" class="required" id="antispam" size="5" />
Where am I going wrong?
EDIT Here is whole form code (generated from PHP script and added to page via AJAX):
<? if ($post = (int) $_POST['pID']) { ?>
<div class="commentform">
<form>
<div class="commenttext">Comment:<br>
<textarea name="comment" class="required"></textarea>
</div>
<div class="commenttext">Your name:<br>
<input type="text" name="name" class="required">
</div>
<div class="commenttext">Your email (will not be publically visible):<br>
<input type="text" name="email" class="required email">
</div>
<div class="commenttext">Type the letters INO here to help us beat spam!<br>
<input name="antispam" type="text" class="required" id="antispam" size="5" />
</div>
<div class="commenttext">
<input type="button" name="submitcomment" class="submitcomment" value="Submit Comment">
<input type="hidden" name="post" value="<?=$post?>">
<? if ($parentComment = (int) $_POST['cID']) { ?>
<input type="hidden" name="parent" value="<?=$parentComment?>">
<? } ?>
</div>
</form>
</div>
<? } ?>
EDIT AGAIN And here's the click delegation code...
$("body").delegate(".submitcomment", "click", function(e) {
e.preventDefault();
var theform = $(this).closest("form");
console.log('Posting comment');
if ($(".commentform form").valid()) {
$.ajax({
type: "POST",
url: "/addComment.php",
data: theform.serialize()
}).done(function(html) {
if (html == 'OK') {
$(theform).html("<div class='commentposted'>Your comment has been received. Thank you. A moderator will review it for public viewing.</div>");
} else {
alert(html);
}
});
}
});
EDIT Here is the code which populates the form into the space where the Reply to Post link was:
$("body").delegate(".getcommentform", "click", function(e) {
e.preventDefault();
var pIDval = $(this).attr("data-pid");
var cIDval = $(this).attr("data-cid");
var thebox = $(this).closest("div.commentformcontainer");
console.log('Getting comment form');
$.ajax({
type: "POST",
url: "/commentForm.php",
data: { pID : pIDval, cID : cIDval }
}).done(function(html) {
thebox.html(html);
});
});
When you need to apply the .validate() method to more than one form, you must wrap it within a jQuery .each().
$(".commentform form").each(function() {
$(this).validate({
rules: {
antispam: {
equalToParam: "INO"
}
}
});
});
EDIT:
You need to initialize the plugin AFTER the form is inserted into the page. Assuming this code properly inserts the form... put your .validate() call as the last item inside...
$("body").delegate(".getcommentform", "click", function(e) {
e.preventDefault();
var pIDval = $(this).attr("data-pid");
var cIDval = $(this).attr("data-cid");
var thebox = $(this).closest("div.commentformcontainer");
console.log('Getting comment form');
$.ajax({
type: "POST",
url: "/commentForm.php",
data: { pID : pIDval, cID : cIDval }
}).done(function(html) {
thebox.html(html);
});
$(".commentform form").validate({ // <- initialize plugin AFTER form is inserted
// your rules & options
});
});
EDIT 2:
Include the equalToParam function someplace on your page within a DOM ready event handler.

open a modeldialog on submit of a form with all values of that form

I have an MVC4.0 website that has a button on a screen. according to my requirement i have submit a hidden form that has some hidden values, on the click of that button. My requirement is that
I have to open a model dialog with all these hidden values.
Please give me some solution.
//under a Beginform of a view this button code is written
<input type="button" id="idBtnScan" name="btnName" value="Scan" onclick="javascript:subProcessURL()" />
//I have add this hidden form on click of this button
//#Model.UDConfig.sScanningURL = is the url of the another website's default page
//Model.UDConfig.listScanData (list) that contains all parameter that takes another website.
<form id="idFormSelect" action ="#Model.UDConfig.sScanningURL" method="post" >
<div class="makeHidden">
#for(int i=0;i<Model.UDConfig.listScanData.Count;i++)
{
<input type="text" id="#Model.UDConfig.listScanData[i].sKey" name="#Model.UDConfig.listScanData[i].sKey" value ="#Model.UDConfig.listScanData[i].sValue" />
}
<input type="text" id="ASPUserSessionId" name="ASPUserSessionId" value="#Session.SessionID" />
<input type="submit" name="SubmitDetails" />
</div>
</form>
<script type ="text/javascript" >
function subProcessID() {
window.showModalDialog("#Model.UDConfig.sScanningURL", "#idFormSelect", "dialogWidth:700px;dialogHeight:500px;scroll:no;")
$("#idFormSelect").submit();
}
</script>
$("#idBtnScan")[0].onclick = function () {
HideDivInfoNErrorMsg();
ShowOverlay_Base();
subProcessURL();
#*$.ajax({
//type: "POST",
//url: "#Url.Action("GetSingleScanURL", "CreationOutward")",
//success: function (data) {
//window.showModalDialog(data, "", "dialogWidth:700px;dialogHeight:500px;scroll:no;")*#
//functionality of view image
$.ajax({
type: "POST",
url: "#Url.Action("ActionViewImage", "CreationOutward")",
success: function (dataImage) {
HideDivInfoNErrorMsg();
if ((dataImage == "Image not found")
|| (dataImage == "Image Folder not found")
|| (dataImage == "Error in processing image")
|| (dataImage == "Multiple Images found")) {
$("#DivInfoNErrorMsg")[0].innerHTML = "<div class=\"errormessage\"><span>".concat(dataImage, "</span></div>");
DisplayInfoNErrorMsg();
}
else {
$("#divImgView")[0].innerHTML = dataImage;
HideDivInfoNErrorMsg();
}
HideOverlay_Base();
}
})
//View Image till here
//}
//}
// )
}
Your button calls a javascript function called 'subProcessURL', but in your code there's only a subProcessID function. These do not match

Categories

Resources