I want to display some text on a text area upon a response from an ajax request.
<div id="wrapper">
<div id="menu">
<p class="welcome">Welcome, <b></b> <%=session.getAttribute( "username" )%> </p>
</div>
<!-- This div will contain the chatlog. -->
<div id="chatbox"></div>
<form name="message" action="" method="post">
<input name="usermsg" type="text" id="usermsg" size="63" />
<input name="submitmsg" type="submit" id="submitmsg" value="Send" />
</form>
</div>
I want to set 'chatbox' text within an ajax request response.
This is the css document for chatbox
#chatbox {
text-align:left;
margin:0 auto;
margin-bottom:25px;
padding:10px;
background:#fff;
height:270px;
width:430px;
border:1px solid #ACD8F0;
overflow:auto; }
This is the ajax call
function loadLog(){
$.ajax({
type: "GET",
url: "HandleMessage",
//contentType: "application/json",
/*data: {
card: JSON.stringify(card)
},*/
success: function(response) {
if(response != null)
{
$("#chatbox").attr("value", "aa"); // I want to concat current value and response here
}
//document.getElementById('chatbox').value = 'fff';
//alert(response);
},
error: function(data) {
alert('errorr');
}
});
Tried many things, but didn't work.
Tried,
$("#chatbox").attr("value", response);
$("#chatbox).val(response);
$(".chatbox").html(response);
This is the preferred way of writing AJAX using jQuery (with deferreds)
$.ajax({
type : "GET",
url : "HandleMessage",
contentType : "application/json",
data : {
card: JSON.stringify(card)
}
})
.done(function(RES){
if( RES )
$("#chatbox")[0].innerHTML += RES;
})
.fail(function(){
alert('error');
});
You want to be using val when updating an input value field
$('#chatbox').val('aa')
In the comment you ask about concatenating the existing field value with the respones:
$('#chatbox').val($('#chatbox').val() + response)
You were close to the solution :
$("#chatbox").html(response);
As described in textContent you can write in javascript:
document.getElementById('chatbox').textContent+= response;
An example, based on github api, is reported in the following snippet (I did not use any format on the output. This is only an example.)
If you neet to get JSON data, using jQuery you may use directly getjson.
function loadLog(e) {
e.preventDefault();
var name = document.getElementById('usermsg').value;
$.ajax({
type: "GET",
url: "https://api.github.com/users/repos",
dataType: "json",
data: {'name': name},
success: function (response) {
if (response != null) {
document.getElementById('chatbox').textContent += JSON.stringify(response,response, 4, 4);
}
},
error: function (data) {
alert('errorr');
}
});
}
window.onload = function () {
document.getElementById('submitmsg').addEventListener('click', loadLog, false);
}
#chatbox {
text-align: left;
margin: 0 auto;
margin-bottom: 25px;
padding: 10px;
background: #fff;
height: 270px;
width: 430px;
border: 1px solid #ACD8F0;
overflow: auto;
}
<script src="https://code.jquery.com/jquery-1.12.3.min.js"></script>
<div id="wrapper">
<div id="menu">
<p class="welcome">Welcome, <b></b> <%=session.getAttribute( "username" )%> </p>
</div>
<!-- This div will contain the chatlog. -->
<div id="chatbox"></div>
<form name="message" action="" method="post">
<input name="usermsg" type="text" id="usermsg" size="63"/>
<input name="submitmsg" type="submit" id="submitmsg" value="Send"/>
</form>
</div>
Related
I'm creating dynamic tabs. I'm currently facing two problems:
When I click on the span x to delete current tab, it deletes all my tabs.
When I getting the array data, it always gets the first tab data only.
Can anyone help me with this? I've tried many ways but I still cannot get my desired result. Here is my fiddle Dynamic Tabs.
Currently my array result looks like this for the 2nd problem when there is two tabs, '2023' and '2025':
[{
February: "1",
January: "1",
Year: "2023"
}, {
February: "1",
January: "1",
Year: "2023"
}]
My expected result would be:
[{
February: "1",
January: "1",
Year: "2023"
}, {
February: "1",
January: "1",
Year: "2025"
}]
$(document).ready(function() {
addTab();
});
$('#add_tab').click(function() {
addTab()
});
//delete current tab
$(".nav-tabs").on("click", "span", function() {
var anchor = $(this).siblings('a');
console.log(anchor)
$(anchor.attr('href')).remove();
$(this).parent().remove();
$(".nav-tabs").children('a').first().click();
});
function addTab() {
var nextTab = $(".nav-tabs").children().length;
var date = new Date().getFullYear() + nextTab;
// create the tab
$('<a class="nav-link" href="#tab-' + date + '" data-toggle="tab">' + date + '</a><span> x </span>').appendTo('#tabs');
// create the tab content
var html = "";
html += '<div class="tab-pane monthSettings" id="tab-' + date + '">';
html += '<label><b>Year: </b></label>';
html += '<input class="txtYear" type="text" value="' + date + '">';
html += '<label><b>January: </b></label>';
html += '<input class="txtJanuary" type="number" value="1">';
html += '<label><b>February: </b></label>';
html += '<input class="txtFebruary" type="number" value="1">';
html += '</div>';
//append to tab-content
var test = $(html).appendTo('.tab-content');
// make the new tab active
$('#tabs a:last').tab('show');
}
//get array
$(document).on('click', '#btnGetArray', function(e) {
var array = []
$(".monthSettings").each(function() {
let detail = {
Year: $(".txtYear").val() || 0,
January: $(".txtJanuary").val() || 0,
February: $(".txtFebruary").val() || 0,
}
array.push(detail)
console.log(array)
});
});
#import url('http://getbootstrap.com/2.3.2/assets/css/bootstrap.css');
.container {
margin-top: 10px;
}
.nav-tabs>a {
display: inline-block;
position: relative;
margin-right: 10px;
}
.nav-tabs>a>span {
display: none;
cursor: pointer;
position: absolute;
right: 6px;
top: 8px;
color: red;
}
.nav-tabs>a>span {
display: inline-block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type="text/javascript" src="https://getbootstrap.com/2.3.2/assets/js/bootstrap.js"></script>
<link rel="stylesheet" type="text/css" href="https://getbootstrap.com/2.3.2/assets/css/bootstrap.css">
<div class="bg-gray-300 nav-bg">
<nav class="nav nav-tabs" id="tabs">
+ Add Year
</nav>
</div>
<div class="card-body tab-content"></div>
<button id="btnGetArray">GetData</button>
The issue is because your selectors for retrieving the .txtYear, .txtJanuary and .txtFebruary will only look at the value of the first element in the collection, no matter how many it finds.
To correct this you can use find() from the parent element, which you can reference from the each() loop, to retrieve the child elements in that iteration.
Taking this a step further, you can simplify the logic by using map() instead of each() to build your array, but the use of find() remains the same.
In addition, there's some other improvements which can be made to the code, such as ensuring all event handlers are within document.ready and using template literals to make the HTML string concatenation easier to read.
jQuery($ => {
$('#add_tab').on('click', addTab);
addTab();
$(".nav-tabs").on("click", "span", function() {
var anchor = $(this).siblings('a');
console.log(anchor)
$(anchor.attr('href')).remove();
$(this).parent().remove();
$(".nav-tabs").children('a').first().click();
});
$(document).on('click', '#btnGetArray', e => {
var array = $(".monthSettings").map((i, container) => ({
Year: $(container).find('.txtYear').val() || 0,
January: $(container).find('.txtJanuary').val() || 0,
February: $(container).find('.txtFebruary').val() || 0,
})).get();
console.log(array);
});
});
function addTab() {
var nextTab = $(".nav-tabs").children().length;
var date = new Date().getFullYear() + nextTab;
$(`<a class="nav-link" href="#tab-${date}" data-toggle="tab">${date}</a><span> x </span>`).appendTo('#tabs');
var html = `
<div class="tab-pane monthSettings" id="tab-${date}">
<label><b>Year: </b></label>
<input class="txtYear" type="text" value="${date}" />
<label><b>January: </b></label>
<input class="txtJanuary" type="number" value="1" />
<label><b>February: </b></label>
<input class="txtFebruary" type="number" value="1" />
</div>`
var test = $(html).appendTo('.tab-content');
// make the new tab active
$('#tabs a:last').tab('show');
}
#import url('http://getbootstrap.com/2.3.2/assets/css/bootstrap.css');
.container {
margin-top: 10px;
}
.nav-tabs>a {
display: inline-block;
position: relative;
margin-right: 10px;
}
.nav-tabs>a>span {
display: none;
cursor: pointer;
position: absolute;
right: 6px;
top: 8px;
color: red;
}
.nav-tabs>a>span {
display: inline-block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script type="text/javascript" src="https://getbootstrap.com/2.3.2/assets/js/bootstrap.js"></script>
<link rel="stylesheet" type="text/css" href="https://getbootstrap.com/2.3.2/assets/css/bootstrap.css">
<div class="bg-gray-300 nav-bg">
<nav class="nav nav-tabs" id="tabs">
+ Add Year
</nav>
</div>
<div class="card-body tab-content"></div>
<button id="btnGetArray">GetData</button>
I'm creating an online text editor. I need to be able to get the users text from the textarea's tag, manipulate this text and bind it back to the textarea, but with HTML in it.
Example:
<textarea v-model="someText"></textarea>
Where someText is set to:
someText: '<b>bold</b>.. not bold'
and should display like:
bold.. not bold
instead of: <b>bold</b>.. not bold
I have a feeling this isn't possible with the textarea tag, but what would be a way to do this?
Typically you would use v-html, but you are correct, inside <textarea> the value will be raw, not processed (will not be bold).
To achieve what you want, maybe you could leverage the contenteditable property to create a <html-textarea>, as below.
Vue.component('html-textarea',{
template:'<div contenteditable="true" #input="updateHTML"></div>',
props:['value'],
mounted: function () {
this.$el.innerHTML = this.value;
},
methods: {
updateHTML: function(e) {
this.$emit('input', e.target.innerHTML);
}
}
});
new Vue({
el: '#app',
data: {
message: 'H<b>ELLO</b> <i>editable</i> Vue.js!'
}
});
div[contenteditable] { border: 1px solid lightblue; }
<script src="https://unpkg.com/vue"></script>
<div id="app">
<html-textarea v-model="message"></html-textarea>
<hr>
<div>
Raw message:
<pre>{{ message }}</pre>
</div>
</div>
I'd have done it this way.
<template>
<div id="app">
<form name="yourform">
<textarea v-model="someText"></textarea>
</form>
</div>
</template>
<script>
export default {
name: 'app',
data () {
return {
someText: 'bold'
}
}
}
</script>
<style scopped>
textarea
{
font-weight:bold;
}
</style>
I am trying to create a jquery autcomplete in ASP.NET MVC, but I have a problem: the results list is not sticking under the input textbox. Here is a printscreen:
http://prntscr.com/c1voo4
This is my HTML :
<link href="#Url.Content("~/Content/themes/base/jquery.ui.all.css")" rel="stylesheet" type="text/css" />
<script src="#Url.Content("~/Scripts/jquery-1.10.2.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery-ui-1.8.11.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/autocomplete.js")" type="text/javascript"></script>
<div>
#using (#Html.BeginForm("Index", "Home", FormMethod.Post))
{
<div class="ui-widget autocomplete-div">
#Html.TextBox("term", null, new
{
id = "autocomplete-textbox",
#class = "form-control",
placeholder = "Enter Name.."
})
<button type="submit" value="Search" class="btn btn-primary" id="autocomplete-button">
<span class="glyphicon glyphicon-search"></span>
</button>
</div>
}
</div>
<script>
$(function () {
$('#autocomplete-textbox').autocomplete({
source: '#Url.Action("AutoComplete")',
minlength: 1
});
});
<script>
And this is my CSS:
#autocomplete-button{
width: 3.5%;
display: inline;
background-color: orangered;
border-color: orangered;
}
#autocomplete-textbox{
width: 17.5%;
display: inline
}
I implemented JQuery Autocomplete in this way and it is working perfectly for me..
$(function(){
var url = '#Url.Action("GetData", "Home")';
$('#txtData').autocomplete({
source: function (request, response) {
$.ajax({
url: url,
data: { 'Prefix': request.term },
type: 'GET',
async: false,
cache: false,
dataType: 'json',
success: function (json) {
response($.map(json, function (data, id) {
return {
label: data,
value: data
};
}));
},
error: function (xmlHttpRequest, textStatus, errorThrown) {
console.log('some error occured', textStatus, errorThrown);
}
});
}
})
On a form with required-validation and ng-messages I use ng-show to hide the directive on startup and only show error messages after the input got ng-dirty.
To still keep the element filling it's space in the layout I have following css rule to overwrite the default ng-hide behaviour:
ng-messages.ng-hide:not(.ng-hide-animate), [ng-messages].ng-hide:not(.ng-hide-animate)
{
display: block !important;
visibility: hidden;
}
When I now enter text in the input field the error message is shortly visible before it is then hidden again (due to the required field being filled). It somehow feels like ng-dirty is resolved before the form validation is done, resulting in this behaviour.
See this Fiddle
or check out the
Code:
var $scope;
var app = angular.module('myapp', ['ngMessages', 'ngAnimate']);
app.controller('UserCtrl', ['$scope', UserCtrl]);
function UserCtrl($scope) {
$scope.showField = true;
$scope.reset = function() {
var master = { name: '' };
$scope.temp = angular.copy(master);
$scope.user_form.$setPristine();
}
}
ng-messages.ng-hide:not(.ng-hide-animate), [ng-messages].ng-hide:not(.ng-hide-animate)
{
display: block !important;
visibility: hidden;
}
ng-messages, [ng-messages]
{
display: block;
height: 1em;
}
input
{
display: block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.8/angular.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.8/angular-animate.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-messages/1.5.5/angular-messages.min.js"></script>
<div ng-app="myapp">
<div ng-controller="UserCtrl">
<form name="user_form" novalidate>
<input name="name" ng-model="temp.name" ng-show="showField" placeholder="Name" required autocomplete="off"/>
<ng-messages ng-show="user_form.name.$dirty" for="user_form.name.$error">
<ng-message when="required">
Please enter your name
</ng-message>
</ng-messages>
<button type="button" class="button" ng-click="reset()">Reset</button>
</form>
<p>
Pristine: {{user_form.$pristine}}
</p>
<pre>Errors: {{user_form.$error | json}}</pre>
</div>
</div>
<ng-messages ng-show="user_form.name.$dirty && !user_form.name.$valid" for="user_form.name.$error">
I have following html file in my visual studio 2013 project
!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
<link href="css/my.css" type="text/css" rel="stylesheet" />
<link rel="stylesheet" type="text/css" href="http://code.jquery.com/mobile/1.4.2/jquery.mobile- 1.4.2.css">
<script type='text/javascript' src='http://code.jquery.com/jquery-1.8.3.js'></script>
<script type="text/javascript" src="http://code.jquery.com/mobile/1.4.2/jquery.mobile-1.4.2.js"></script>
<link rel="stylesheet" type="text/css" href="http://code.jquery.com/mobile/1.4.2/jquery.mobile-1.4.2.css">
<script type='text/javascript' src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.min.js"></script>
<script type='text/javascript' src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/additional-methods.js"></script>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style type="text/css">
#loginBody {
color: aqua;
}
</style>
<script type='text/javascript'>
$(document).on('pageinit', function () {
//$.support.cors =true,
//$.mobile.allowCrossDomainPages = true;
$('#frmLogin').validate(
{
rules: {
username: {
required: true
},
password: {
required: true
}
},
messages: {
username: {
required: "Please enter your username."
},
password: {
required: "Please enter your password."
}
},
errorPlacement: function (error, element) {
error.appendTo(element.parent().prev());
},
submitHandler: function (form) {
//$("#frmLogin").submit(function (event) {
//event.preventDefault();
var credentials = { username: $("#username").val(), password: $("#password").val() };
$.ajax({
type: "POST",
url: "api/auth", // this url is just a placeholder
cache: false,
data: JSON.stringify(credentials),
contentType: "application/json; charset=utf-8",
success: function(data,status,jqxhr)
{
//validate the response here, set variables... whatever needed
//and if credentials are valid, forward to the next page
if (data.status == "success")
{
var obj = $.parseJSON(data);
localStorage.setItem("acccessToken", obj.accessToken);
alert(obj.accessToken);
$(":mobile-pagecontainer").pagecontainer ("change", "Authorization.html", { role: "page" });
//window.location.href = "http://www.jqueryvalidation.org";
}
else if(data.status== "error")
{
alert("Authentication Invalid.Please try again!");
return false;
}
//or show an error message
},
error: function (jqxhr, status, errorMsg)
{
// server couldn't be reached or other error
alert("jqXHR Status : " + jqxhr.status + " Status: " + status + " Error: " + errorMsg);
}
}, "json");
return false;
}//);
});
});
</script>
<style type="text/css">
label.error
{
color: red;
font-size: 16px;
font-weight: normal;
line-height: 1.4;
margin-top: 0.5em;
width: 100%;
float: none;
}
#media screen and (orientation: portrait){
label.error { margin-left: 0; display: block; }
}
#media screen and (orientation: landscape){
label.error { display: inline-block; margin-left: 22%; }
}
em { color: red; font-weight: bold; padding-right: .25em; }
</style>
</head>
<body id="loginBody">
<div data-role="page" id="login">
<div data-role="header">
<h1> Intergraph </h1>
</div>
<div data-role="content">
<form id="frmLogin" method="post" action="api/auth" data-ajax="false">
<div data-role="fieldcontain">
<label for="username">
<em>* </em> Username:
</label>
<input type="text" id="username"
name="username" />
</div>
<div data-role="fieldcontain">
<label for="password">
<em>* </em>Password:
</label>
<input type="password" id="password"
name="password" />
</div>
<div class="ui-body ui-body-b">
<button class="btnLogin" type="submit" id="loginBtn"
data-theme="a">
Login
</button>
</div>
</form>
</div>
<!--<div data-role="page" id="success" data-theme="b">
<div data-role="header">
<h1>Thank You!!!</h1>
</div>
</div>-->
</div>
</body>
</html>
And here is code inside my my.css file
#loginBody
{
background: url('../images/my-generic-curved-background.png') no-repeat fixed center bottom;
background-size:390px 320px; color:blue;
}
#loginContent
{
text-align:center;
margin-top:210px;
color:aquamarine;
}
Now the weird thing is this file is not read or not loaded (I'm not sure and even I don't know how to ascertain that) but when I replace #loginBody selector with * (all) I can see the image in the background of the page is displayed and also blue color in the portion of the page which is not covered by the image (so may be my.css file is getting loaded on the run , I would suppose). So precisely what I mean is that css rules are getting applied on for * (all) selector and other selectors too but not for #loginBody selector, why is that?
All ideas and suggestions will be highly appreciated.
Thanks
You need to override the base styles setup by JQM. The .ui-overlay-a class sets colours that you aren't overriding and you've also placed your my.css before any JQM includes. To override, your my.css must be last in the link includes and you need to use !important.
I would suggest heading to the bottom of the official themes page and look through the overrides for each section. They don't provide information on background images but it will show you what the capabilities are out-of-the-box.
http://demos.jquerymobile.com/1.0rc2/docs/api/themes.html
The data-theme attribute can be applied to the header and footer
containers to apply any of the lettered theme color swatches. While
the data-theme attribute could be added to the content container, we
recommend adding it instead to div or container that has been assigned
the data-role="page" attribute to ensure that the background color is
applied to the full page.
I'd also suggest using developer tools to inspect the elements and how JQM is settings styles. In Chrome/FF you right click on an element and select Inspect Element.