I'm currently trying to modify a text input's value and add a "v" as a pre-fix before the POST. This code is correctly changing the value and updating the field (i.e. I can see it add the 'v' after the submit), but if I look at the POST request in the debugger I an see the value does not contain the desired result. It just has whatever the original input was. Below is my code, what am I not connecting here?
$(document).on("ready", function() {
$('#stb-form').on("submit", function(e) {
var value = $('#gitVersionInput').val();
if (value === "") {
e.preventDefault();
return false;
}
var gitTag = 'v' + value;
$('#git-version').val(gitTag);
console.log(gitTag);
$(".modal").modal('show');
this.submit();
});
});
Try submitting the form using a normal input of type button rather than type submit.
<input type="button" id="form-submit" value="Submit">
$('#form-submit').on("click", function(e) {
var value = $('#gitVersionInput').val();
if (value === "") {
e.preventDefault();
return false;
}
var gitTag = 'v' + value;
$('#git-version').val(gitTag);
console.log(gitTag);
$(".modal").modal('show');
$('#stb-form').submit();
});
Related
I have a button that triggers a kartik dialog.prompt, where text is put in.
I need the input in the dialog to have several rows and line breaking capability (like textarea)
How to change it from a simple text input to textarea?
Here is my javascript:
$("#bulk-email-button-invitations").on("click", function() {
var grid = $("#invitations");
var keys = grid.yiiGridView('getSelectedRows');
if (keys.length >= 1){
krajeeDialog.prompt({label:'Text emailu:', placeholder:'Zadejte text emailu'}, function (result) {
if (result) {
$(location).attr('href', '/educational-event-invitation/bulk-email?' + $.param({invitations: keys, text: result}));
} else {
krajeeDialog.alert('Text emailu nesmí být prázdný!');
}
});
}else{
krajeeDialog.alert("Nejprve vyberte studenty, kterým chcete poslat email!")
}
});
I found that if type is not defined (unlike label and placeholder in my case), it defaults to "text". But I wasn't able to make the dialog render any type other than a simple one-row text input.
Apparently, this is not supported in the extension.
Reason:
The reason is that in the dialog.js where the KrajeeDialog.prototype is defined the function bdPrompt is the one that takes care of the prompt dialog that is to be created and it creates the default field type as input rather than deciding on any of the options or parameters passed to KrajeeDialog.prompt() although you can pass a parameter of name type like
krajeeDialog.prompt({
label:'Text emailu:',
placeholder:'Zadejte text emailu',
type:'password'
},function(){})
but this does not decide if the element will be input or textarea type, this parameter type is passed as the attribute of the input element. See the below code block to understand the reason i explained the third line will always create a field of type input.
File yii2-dialog/assets/js/dialog.js Line 110
if (typeof input === "object") {
$inputDiv = $(document.createElement('div'));
$input = $(document.createElement('input'));
if (input['name'] === undefined) {
$input.attr('name', 'krajee-dialog-prompt');
}
if (input['type'] === undefined) {
$input.attr('type', 'text');
}
if (input['class'] === undefined) {
$input.addClass('form-control');
}
$.each(input, function(key, val) {
if (key !== 'label') {
$input.attr(key, val);
}
});
if (input.label !== undefined) {
msg = '<label for="' + $input.attr('name') + '" class="control-label">' + input.label + '</label>';
}
$inputDiv.append($input);
msg += $inputDiv.html();
$input.remove();
$inputDiv.remove();
} else {
msg = input;
}
So you might need to override the javascript function according to your needs if you want to work it that way.
It is possible to add custom html to krajeeDialog.prompt after all.
In the documentation, kartik-v states:
content: string|object: If set as a string, it is treated as a raw HTML content that will be directly displayed.
So if I replace the original object in my code with a string containing the desired html, it will render my textarea or any other form element.
For example, replace it with a textarea html:
$("#bulk-email-button-invitations").on("click", function() {
var grid = $("#invitations");
var keys = grid.yiiGridView('getSelectedRows');
if (keys.length >= 1){
krajeeDialog.prompt('<textarea>Sample text...</textarea>', function (result) {
if (result) {
$(location).attr('href', '/educational-event-invitation/bulk-email?' + $.param({invitations: keys, text: result}));
} else {
krajeeDialog.alert('Text emailu nesmí být prázdný!');
}
});
}else{
krajeeDialog.alert("Nejprve vyberte studenty, kterým chcete poslat email!")
}
});
The following code loops when the page loads and I can't figure out why it is doing so. Is the issue with the onfocus?
alert("JS is working");
function validateFirstName() {
alert("validateFirstName was called");
var x = document.forms["info"]["fname"].value;
if (x == "") {
alert("First name must be filled out");
//return false;
}
}
function validateLastName()
{
alert("validateLastName was called");
var y = document.forms["info"]["lname"].value;
if (y == "") {
alert("Last name must be filled out");
//return false;
}
}
var fn = document.getElementById("fn");
var ln = document.getElementById("ln");
fn.onfocus = validateFirstName();
alert("in between");
ln.onfocus = validateLastName();
There were several issues with the approach you were taking to accomplish this, but the "looping" behavior you were experiencing is because you are using a combination of alert and onFocus. When you are focused on an input field and an alert is triggered, when you dismiss the alert, the browser will (by default) re-focus the element that previously had focus. So in your case, you would focus, get an alert, it would re-focus automatically, so it would re-trigger the alert, etc. Over and over.
A better way to do this is using the input event. That way, the user will not get prompted with an error message before they even have a chance to fill out the field. They will only be prompted if they clear out a value in a field, or if you call the validateRequiredField function sometime later in the code (on the form submission, for example).
I also changed around your validation function so you don't have to create a validation function for every single input on your form that does the exact same thing except spit out a slightly different message. You should also abstract the functionality that defines what to do on each error outside of the validation function - this is for testability and reusability purposes.
Let me know if you have any questions.
function validateRequiredField(fieldLabel, value) {
var errors = "";
if (value === "") {
//alert(fieldLabel + " must be filled out");
errors += fieldLabel + " must be filled out\n";
}
return errors;
}
var fn = document.getElementById("fn");
var ln = document.getElementById("ln");
fn.addEventListener("input", function (event) {
var val = event.target.value;
var errors = validateRequiredField("First Name", val);
if (errors !== "") {
alert(errors);
}
else {
// proceed
}
});
ln.addEventListener("input", function (event) {
var val = event.target.value;
var errors = validateRequiredField("Last Name", val);
if (errors !== "") {
alert(errors);
}
else {
// proceed
}
});
<form name="myForm">
<label>First Name: <input id="fn" /></label><br/><br/>
<label>Last Name: <input id="ln"/></label>
</form>
Not tested but you can try this
fn.addEventListener('focus', validateFirstName);
ln.addEventListener('focus', validateLastName);
I am doing a calculator program in javascript and HTML. I have a button with a value '=' in it. In that one when a user click on "=" button in calculator. it should start evaluate the input he/she had given so far. But when a user click '=' button i tried to compare like this
$(".calcinput").click(function () {
var res = $(this).val();
if (res == '=') {
//code to handle when '=' is pressed;
}
}
but it didn't work please help me.
Your code is good enough to handle the event .. Just add an extra = in comapre
$(".calcinput").click(function () {
var res = $(this).val();
//if (res == '=') {
if (res === '=') {
//code to handle when '=' is pressed;
}
});
Next check where you used div or button or something else element to represent the button =
If it is button then use val() to extract the value
var res = $(this).val();
If the element is div then it could be innerHTML or innerTEXT
var res = $(this).innerHTML;
//Or
var res = $(this).innerText;
You can add an extra line to check whether you getting proper value of element
var res = $(this).val();
alert(res);
You can also use $(this).val() provided you have non empty value attribute in the button
HTML
<button class ="calcinput" type ="button">1</button>
<button class ="calcinput" type ="button">2</button>
<button class ="calcinput" type ="button" value="=">=</button>
JS
$(".calcinput").on('click',function(){
if($(this).val() === "="){
alert("equal");
}
})
WORKING FIDDLE
use
$(this).text()
to retrieve button text instead of
$(this).val()
in your code
= is text of button element and not value. Due to which .val() returns empty string. hence you need to use .text() instead of .val here:
$(".calcinput").click(function () {
var res = $(this).text();
if (res == '=') {
//code to handle when '=' is pressed;
}
});
check out this Demo . I have done a operation for ADD Simillarly you can do it for all operations ..keep it simple
A<input type="text" class="a" /><br/>
B<input type="text" class="b" />
<input type="button" class="calcinput" />
$(".calcinput").click(function () {
var res1 = $(".a").val();
var res2 = $(".b").val();
alert(parseFloat(res1) + parseFloat(res2));
});
How do I make a script in javascript to output an error and prevent form submission with empty fields in the form? Say the form name is "form" and the input name is "name". I have been having some trouble with PHP not always handling the empty fields correctly, so I would like this as a backup. Any help is appreciated, thanks.
HTML Code :-
<form name='form'>
<input type="button" onclick="runMyFunction()" value="Submit form">
</form>
Javascript Code :-
function runMyFunction()
{
if (document.getElementsByName("name")[0].value == "")
{
alert("Please enter value");
}
else
{
var form= document.getElementsByName("form")[0];
form.submit();
}
}
Claudio's answer is great. Here's a plain js option for you. Just says to do nothing if field is empty - and to submit if not.
If you need to validate more than one, just add an && operator in the if statement and add the same syntax for OtherFieldName
function checkForm(form1)
{
if (form1.elements['FieldName'].value == "")
{
alert("You didn't fill out FieldName - please do so before submitting");
return false;
}
else
{
form1.submit();
return false;
}
}
This is untested code but it demonstrates my method.
It will check any text field in 'form' for empty values, and cancel the submit action if there are any.
Of course, you will still have to check for empty fields in PHP for security reasons, but this should reduce the overhead of querying your server with empty fields.
window.onload = function (event) {
var form = document.getElementsByName('form')[0];
form.addEventListener('submit', function (event) {
var inputs = form.getElementsByTagName('input'), input, i;
for (i = 0; i < inputs.length; i += 1) {
input = inputs[i];
if (input.type === 'text' && input.value.trim() === '') {
event.preventDefault();
alert('You have empty fields remaining.');
return false;
}
}
}, false);
};
Attach an event handler to the submit event, check if a value is set (DEMO).
var form = document.getElementById('test');
if (!form.addEventListener) {
form.attachEvent("onsubmit", checkForm); //IE8 and below
}
else {
form.addEventListener("submit", checkForm, false);
}
function checkForm(e) {
if(form.elements['name'].value == "") {
e.preventDefault();
alert("Invalid name!");
}
}
I'm trying to have two functions checking each form input, one for onchange() and the other for onkeypress(); my reason for this would be to show if the input was valid once you leave the input field using onchange() or onblur(), and the I also wanted to check if the input field was ever empty, to remove the message indicating that bad input was entered using onkeypress() so that it would update without having to leave the field (if the user were to delete what they had in response to the warning message.)
It simply isn't working the way I intended, so I was wondering if there was something obviously wrong.
My code looks like this:
<form action="database.php" method = post>
Username
<input type='text' id='un' onchange="checkname()" onkeypress="checkempty(id)" />
<div id="name"></div><br>
.....
</form>
And the Javascript:
<script type="text/javascript">
function checkname() {
var name = document.getElementById("un").value;
var pattern = /^[A-Z][A-Za-z0-9]{3,19}$/;
if (name.search(pattern) == -1) {
document.getElementById("name").innerHTML = "wrong";
}
else {
document.getElementById("name").innerHTML = "right!";
}
}
function checkempty(id) {
var temp = document.getElementById(id).value;
if (!temp) {
document.getElementById("name").innerHTML = '';
}
}
</script>
Per your clarification in the comments, I would suggest using the onkeyup event instead of onkeypress (onkeypress only tracks keys that generate characters - backspace does not). Switching events will allow you to validate when the user presses backspace.
Here's a working fiddle.
Edit:
See this SO question for further clarification: Why doesn't keypress handle the delete key and the backspace key
This function should below should check for empty field;
function checkempty(id) {
var temp = document.getElementById(id).value;
if(temp === '' || temp.length ===0){
alert('The field is empty');
return;
}
}
//This should work for check name function
function checkname() {
var name = document.getElementById("un").value;
var pattern = /^[A-Z][A-Za-z0-9]{3,19}$/;
if (!name.test(pattern)) {
document.getElementById("name").innerHTML = "wrong";
}
else {
document.getElementById("name").innerHTML = "right!";
}
}